2

I have a form control nameFormControl with some validators and an updateOn property:

ngOnInit(): void {
    this.myFormGroup = this.fb.group({
      nameFormControl: ["john", {
        validators: [Validators.required, Validators.minLength(10)]
        , updateOn: "blur"
      }]
    });
  }

I want to fire the validators on blur event only. But when the form loads for the first time, validators are firing immediately and setting both nameFormControl and myFormGroup's invalid property to true because nameFormControl's initial value length is 4. How can I skip firing the validators until blur operation happens?

I am using:

Angular CLI: 14.2.4
Node: 14.17.3
Angular: 14.2.4
0

1 Answer 1

2

One solution would be to implement your own Validator function and using a boolean inside your component which deactivates the controls inside the Validator on the first time they are done (when Angular runs the validators at the very start).

Something like:

public isFirstControl:boolean = true;

And:

customValidator(): ValidatorFn {
    return (control:AbstractControl) : ValidationErrors | null => {
      if(this.isFirstControl){
        this.isFirstControl = false;
        return null;
      }

      //Your actual validation logic here
      if(toto){
        return { required: true };
      }
      return null;
    }
  }

Then give this validator function to your FormControl.

Sign up to request clarification or add additional context in comments.

Comments

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.