Skip to content Skip to sidebar Skip to footer

Don't Validate Untouched Fields In Angular2

I have reactive form and don't want validation to be triggered until user really visits a field. For example, this is a field:

Solution 1:

As somebody mentioned in the comments:

Initial config:

customerNumber: FormControl = new FormControl(null);

Subscribe to value changes and set your validator only if a validator is not already set:

this.sub = this.form.controls.customerNumber.valueChanges.subscribe(value => {
   if (!this.form.controls.customerNumber.validator) {  
       this.form.controls.customerNumber.setValidators(Validators.required);
   }
})

If you need to perform validation on the value that triggered validator setup make sure to call:

this.form.controls.customerNumber.updateValueAndValidity();

immediately after the setup.

Also, make sure to unsubscribe once you are done with the component:

ngOnDestroy() {
    this.sub.usubscribe();
}    

EDIT

Another option would be to create a custom required validator that validates only if the control is dirty.:

import { FormControl } from'@angular/forms';

functioncustomRequiredValidator(c: FormControl) {
    if(!c.dirty)
    {
      returnnull;
    }
    ...
}

You can then just import it wherever needed and use it in place of the Validators.required.

Post a Comment for "Don't Validate Untouched Fields In Angular2"