将自定义验证器拆分为多个功能Angular 2

时间:2018-09-07 10:03:26

标签: angular angular2-forms angular-reactive-forms angular-validation

    export class FormFieldErrorExample {
      email = new FormControl('', [Validators.required, Validators.email, this.lengthValidator]);

      getErrorMessage() {
        return this.email.hasError('required') ? 'You must enter a value' :
            this.email.hasError('email') ? 'Not a valid email' :
                'minimum length should be greater than 10';
      }
      lengthValidator(control : AbstractControl){

        if(control.value.length <10)    
        return {lengthError : true};
        else return this.anotherValidator(control);
      }
anotherValidator(control: AbstractControl){

 return {lengthError : true};
}

我试图将验证器拆分为另一个函数,但收到类似“无法读取未定义的属性' anotherValidator ”的错误。 如何将验证器拆分为多个功能并正确传递控件

https://stackblitz.com/edit/angular-psfasq-5yxaln

1 个答案:

答案 0 :(得分:1)

您应该使用bind()this的上下文传递给您的customvalidator lengthValidator

email = new FormControl('', [Validators.required, Validators.email, this.lengthValidator.bind(this)])