aurelia验证插件的介绍包含一个关于通过扩展ValidationRule类并将其传递给class函数来创建自定义ValidationRule的部分。给出的例子如下:
import {ValidationRule} from './plugins/validation/';
export class MyValidationRule extends ValidationRule{
constructor (isValid) {
super(
isValid, //pass any object as 'threshold'
(newValue, threshold) => { //pass a validation function
return threshold;
}
(newValue, threshold) => { //Optionally pass a function that will provide an error message
return `needs to be at least ${threshold} characters long`;
},
);
}
}我该怎么处理这个?例如,为了演示的目的,如果我想创建一个函数来检查这个值是否是一个带有regex的电话号码,我如何使用这个模板编写代码呢?我问这个问题是因为文档中没有示例;没有一个用于编写自定义验证规则,而另一个示例展示了如何将一个添加到ValidationGroup原型中,但我想知道添加自定义规则的两种方法
发布于 2015-12-01 07:51:16
首先,您不必创建自定义验证规则类。您可以只创建一个接受参数并返回验证结果的函数。
function validatePhoneNumber(newValue) {
return true/*your RegExp check should return true/false here*/;
}然后
this.validation = validation.on(this)
.passes(validatePhoneNumber);如果您认为需要一个类来使验证变得更通用,请尝试如下
import {ValidationRule} from './plugins/validation/';
export class RegExpValidationRule extends ValidationRule {
constructor (regExp, errorMessage) {
super(
regExp,
(newValue, threshold) => {
return true/*your RegExp check should return true/false here*/;
},
(newValue, threshold) => {
return errorMessage;
}
);
}
}然后
var validationRule = new RegExpValidationRule(/*your RegExp*/, 'Invalid phone number');
this.validation = validation.on(this)
.passesRule(validationRule);https://stackoverflow.com/questions/33994548
复制相似问题