Angular 4 remove required validator conditionally
In Angular 4 app I have a form model like this:
this.form = this._fb.group({
title: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
description: ['', [Validators.required, Validators.minLength(3)]]
});
Now what I want is to remove dynamically only the required validator from the control validators array. Something like this:
saveDraft() {
this.form.controls['title'].removeValidator('required'); //Just a fake implementation for demonstration
}
This question is not the duplicate of the mentioned question. My case is different I just want to remove the required validator unknowingly the other ones.
if you want to add validation try this one.
saveDraft() {
this.form.get('title').setValidators([Validators.required, Validators.minLength(3)]);
this.form.get('title').updateValueAndValidity();
}
if you want to remove validators try this one.
saveDraft() {
this.form.get('title').clearValidators();
this.form.get('title').updateValueAndValidity();
}
I don't like clearing and setting validators, as I have to repeat all static validators (patterns, min, max, etc.) just to have a dynamic "required" validator.
I use a conditional validator:
export function conditionalValidator(condFn: (control: AbstractControl) => boolean,
validators: ValidatorFn | ValidatorFn[]): ValidatorFn {
return (control) => {
if (!condFn(control)) {
return null;
}
if (!Array.isArray(validators)) {
return validators(control);
}
return validators.map(v => v(control)).reduce((errors, result) =>
result === null ? errors :
(Object.assign(errors || {}, result))
);
};
}
I can then mix a static validator with a dynamic "required" condition:
this.fb.group({name: ['', [Validators.minLength(4),
conditionalValidator(this.isClientProj, Validators.required)]]}
Where isClientProj()
is the condition function (closure)
we can use setValidators
to remove validation.
setValidators(newValidator: ValidatorFn | ValidatorFn[]): void
setValidators() - setValidators programmatically adds the sync validators. This method will remove all the previously added sync or async validators.
this.form.get('title').setValidators(null);
this.form.get('title').setErrors(null);