gpt4 book ai didi

javascript - Breeze:如何根据另一个属性的值验证一个属性

转载 作者:行者123 更新时间:2023-11-28 00:42:07 25 4
gpt4 key购买 nike

我在 Breeze 数据属性中使用了多个验证器。下面是使用的 Breeze 模式:

         {
"name": "property",
"dataType": "String",
"validators": [
{
"name": "required",
"context": {
//Data for Processing
}
},
{
"name": "maxLength",
"context": {
//Data for processing
}
}
]
}

在上述架构中,required 规则将首先执行,无论第一个验证器的结果如何,都会执行“maxLength”验证器。因此,即使该字段不是必需的,也会执行 maxLength 规则并捕获validationErrors。

有没有办法根据所需验证器的结果运行 maxLength 验证器?

提前致谢。

最佳答案

如果您希望在属性 A 具有特定值时使属性 B 成为必需,请不要使用标准必需验证器。写一个custom validator

下面是一个示例,其中将自定义验证器添加到 propertyB,使得仅当 propertyA 为 true 时才需要 propertyB。

这是可能的,因为 Breeze 传递给验证器函数的上下文参数包含一个“实体”属性,您可以访问该属性来检查 propertyA 的值。

propertyB.validators.push(
new breeze.Validator(
"myCustomValidator",
function(value, context) {
// when propertyA is false, skip validation.
if (!context.entity.propertyA)
return true;

// validate the value is a string.
if (typeof value !== 'string')
return false;

// validate the value is not an empty string.
return value !== null && value.length > 0;
},
{
messageTemplate: "'%displayName%' must be a string and is required when property A is true."
})
);

关于javascript - Breeze:如何根据另一个属性的值验证一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27807141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com