0
    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

1 Answer 1

1

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

email = new FormControl('', [Validators.required, Validators.email, this.lengthValidator.bind(this)])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you saved my day!! .bind(this) works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.