如何编写自定义 ValidationRule
How to write a custom ValidationRule
aurelia-validation 插件的介绍包含一个关于创建自定义 ValidationRules 的部分,方法是扩展 ValidationRule class 并将其传递给传递函数。给出的例子如下:
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`;
},
);
}
}
我该怎么办?例如,出于演示目的,如果我想创建一个函数来检查该值是否为带有正则表达式的 phone 数字,我将如何使用此模板对其进行编码?我问是因为文档中的示例很少;有 none 用于编写自定义验证规则,另一个示例显示了如何将一个添加到 ValidationGroup 原型,但我想知道添加自定义规则的两种方法
首先,您不必创建自定义验证规则 class。您可以只创建一个接受参数和 returns 验证结果的函数,例如
function validatePhoneNumber(newValue) {
return true/*your RegExp check should return true/false here*/;
}
然后是
this.validation = validation.on(this)
.passes(validatePhoneNumber);
如果您认为需要 class 来使验证更通用,请尝试
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);
aurelia-validation 插件的介绍包含一个关于创建自定义 ValidationRules 的部分,方法是扩展 ValidationRule class 并将其传递给传递函数。给出的例子如下:
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`;
},
);
}
}
我该怎么办?例如,出于演示目的,如果我想创建一个函数来检查该值是否为带有正则表达式的 phone 数字,我将如何使用此模板对其进行编码?我问是因为文档中的示例很少;有 none 用于编写自定义验证规则,另一个示例显示了如何将一个添加到 ValidationGroup 原型,但我想知道添加自定义规则的两种方法
首先,您不必创建自定义验证规则 class。您可以只创建一个接受参数和 returns 验证结果的函数,例如
function validatePhoneNumber(newValue) {
return true/*your RegExp check should return true/false here*/;
}
然后是
this.validation = validation.on(this)
.passes(validatePhoneNumber);
如果您认为需要 class 来使验证更通用,请尝试
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);