Please assist, I want to remove all validators in form, Please advise whether it's possible or not and if not, what's the better way to remove validators if you have a form Group of 20 or more form controls, see example below.
ngOnInit() {
this.exampleFormGroup = this.formBuilder.group({
surname: ['', [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]],
initials: ['', [Validators.required, Validators.maxLength(4)]]
});
}
public removeValidators() {
this.exampleFormGroup.get('surname').clearValidators();
this.exampleFormGroup.get('initials').clearValidators();
this.exampleFormGroup.updateValueAndValidity();
}
public addValidators() {
this.exampleFormGroup .get('surname').setValidators([Validators.required,Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]);
this.exampleFormGroup.get('initials').setValidators([Validators.required, Validators.maxLength(4)]);
this.exampleFormGroup.updateValueAndValidity();
}
The above method addValidators()
will add validators and removeValidators()
will remove validators when executed. But the problem I have is, I have to specify the form control I'm trying to clear validators. Is there a way to just do this.exampleFormGroup.clearValidators();
and clear all in the form and again this.exampleFormGroup.setValidators()
to set them back? I know I may be asking for a unicorn, but in a scenario where the formGroup has 20 or more controls, clearing and setting validators can be painful, so a map on how to handle such scenarios will be much appreciated.
form.get(key).clearValidators(); form.get(key).updateValueAndValidity();
solved my issue. Note: If someone calls the method insideform.valueChanges.pipe().subscribe(...)
and still makes changes inside the same, should remember to setform.get(key).updateValueAndValidity({withEvents: false})
, otherwise you will get into an infinite loop, leading to a stack overflow problem. – Peyote