如何编写自定义ValidationRule

时间:2015-11-30 08:46:43

标签: aurelia aurelia-validation

aurelia-validation插件的介绍包含有关创建自定义ValidationRules的部分,通过扩展ValidationRule类并将其传递给pass函数。给出的例子如下:

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`;
        },
    );
}
}

我该怎么办?例如,出于演示目的,如果我想创建一个函数来检查该值是否是带有正则表达式的电话号码,我将如何使用此模板进行编码?我问,因为文档很少有例子;没有用于编写自定义验证规则,另一个示例显示如何将一个添加到ValidationGroup原型,但我想知道添加自定义规则的两种方法

1 个答案:

答案 0 :(得分:3)

首先,您不必创建自定义验证规则类。您可以创建一个接受参数的函数并返回验证结果,例如

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);