Search code examples
angularangular2-formsangular-reactive-formsangular-validation

Split Custom Validator into multiple Functions Angular 2


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

I have tried to split the validator into another function but getting an error like 'Cannot read property 'anotherValidator' of undefined'. How can i split the validator into multiple functions and pass the control properly

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


Solution

  • You should pass the context of this to your customvalidator lengthValidator using bind()

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