反应形式的多个自定义验证器 angular 2

multiple custom validators in reactive form angular 2

我在 reactive form 中有两个自定义 validator,我调用下面的函数在组件构造函数中创建表单:

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
    newpassword : [null, Validators.required],
    passwordconfirm: [null, Validators.required]
},
{
    validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule] // validation method

});

}

PasswordValidation 是一个 class 具有如下两个函数

    export class PasswordValidation {

     public  static PasswordMatch(control: AbstractControl) {
        let password = control.get('newpassword'); // to get value in input tag
        if(password){
            let confirmPassword = control.get('passwordconfirm').value; // to get value in input tag
            if (password.value !== confirmPassword) {
                control.get('passwordconfirm').setErrors({ ['passwordmatch'] : true});
            }else {
                return null;
            }
        }
    }

    public static PasswordRule(control: AbstractControl) {
        let password = control.get('newpassword').value; // to get value in input tag
        let pattern = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,64}');               
        if (!pattern.test(password)) {
            control.get('newpassword').setErrors({ ['passwordrule'] : true});
        }else if (password.toLowerCase() === 'something') {
            control.get('newpassword').setErrors({ ['passwordrule'] : true});
        }else {
            return null;
        }
    }
}

每个自定义验证器都像这样单独工作

validator: PasswordValidation.PasswordMatch

或这个

validator: PasswordValidation.PasswordRule

但在数组中使用它们,如

validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule]

出现错误this.validator is not a function并且不起作用,我不知道,请帮忙。

最好使用 Validators.compose([]),它接受要在表单组中的特定用户控件上使用的验证器数组。

例如,如果您想针对 passwordconfirmnewpassword 控件添加验证器,您可以像下面那样做

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
    newpassword : [null, Validators.compose([Validators.required,PasswordValidation.PasswordRule])],
    passwordconfirm: [null, Validators.compose([Validators.required, PasswordValidation.PasswordMatch])]
});

在幕后,这就是代码的样子

group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null): FormGroup {
  const controls = this._reduceControls(controlsConfig);
  const validator: ValidatorFn = isPresent(extra) ? extra['validator'] : null;
  const asyncValidator: AsyncValidatorFn = isPresent(extra) ? extra['asyncValidator'] : null;
  return new FormGroup(controls, validator, asyncValidator);
}

你可以看到参数 validator 实际上是一种接口类型 ValidatorFn 如下所示

interface ValidatorFn { 
  (c: AbstractControl): ValidationErrors|null
}

所以你可以看到它可以接受任何具有上述签名的方法。

来源:https://angular.io/api/forms/ValidatorFn

查看此 link 了解更多信息:https://toddmotto.com/reactive-formgroup-validation-angular-2