Angular中reactive form模式自定义验证器

在reactive form模式中自定义验证器,其实就是定义一个返回ValidatorFn类型的函数就可以。函数参数可以随便定义,符合语法解释就可以。

而ValidatorFn这个接口是这样定义的:{(key:string): any}。一般是如果验证成功返回null,验证失败则返回{’checkError‘: true}这样一个对象结构就可以。

这里的’numberCheck‘是本篇随笔任意定义的,具体的可以根据自己的需要替换成自己需要的就可以。有一点需要注意,上述失败返回对象中,值是true

还是false不影响使这个验证失败。也就是说,只有当验证方法返回null这一种情况时,验证才算成功,其他情况均表示失败。

下面附加一个方法事例:

customValidator(validatingValue: any): ValidatorFn {

    return (c: AbstractControl) => {

        // 以下开始可以使用本方法的参数和箭头函数本身的参数(c)

        if (validatingValue !== c.value) {

            return {'checkError': true};

        } else {

            return null;

        }

    };

}

猜你喜欢

转载自www.cnblogs.com/sagaminosakura/p/9831646.html
今日推荐