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

时间:2017-09-09 11:53:23

标签: angular angular-reactive-forms custom-validators angular-forms angular-validation

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

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

});

}

PasswordValidation 是一个包含两个函数的类,如下所示

    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并且不起作用,我不知道,请帮忙。

1 个答案:

答案 0 :(得分:4)

最好使用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

点击此链接了解更多信息:https://toddmotto.com/reactive-formgroup-validation-angular-2