Home > Net >  Angular validation firing immediately on form initialization
Angular validation firing immediately on form initialization

Time:10-09

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

CodePudding user response:

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.

  • Related