74

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.

1

10 Answers 10

137

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();
}
5
  • This doesn't work for me. In my case I have dropdown on change event I am calling a function a condition to set the validators as above. Any suggestions what might be wrong.
    – Zaker
    Commented Mar 19, 2018 at 9:52
  • @Zaker Please post a new question, with your code, and link to this question.
    – rmcsharry
    Commented Mar 20, 2018 at 18:36
  • 9
    for anyone else running into this issue, I had to do a this.form.get('title').setValidators(null); this.form.get('title').setErrors(null) in order to ensure this.form.valid = true Commented Sep 13, 2018 at 16:34
  • 3
    @CalebSwank Thanks for adding this. setErrors(null) and setValidators(null); works charmingly. :-)
    – Raj
    Commented Oct 25, 2018 at 7:40
  • But after removing errros when you add required validator again, you need add errors :(.
    – ohdev
    Commented Nov 8, 2019 at 15:35
8

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)

2
  • I think something to note here is that something needs to be done to insure that a change in the condition value triggers revalidation. I don't think a change in a checkbox will trigger validation on other form fields.
    – LameCoder
    Commented Jan 9, 2019 at 18:36
  • Right, and this is the problem I am currently trying to solve. If you're in an invalid state and the validator condition changes to false, then the form is still invalid unless you manually kick off a validation cycle which is less than desirable. The Validator interface does define a changed event hook which as far as I can tell is what Angular hooks into to trigger validation again, so I'm going to try that.
    – dudewad
    Commented Jan 29, 2019 at 23:41
8

You can use: AbstractControl.removeValidators(validator: ValidatorFn)

Not sure if it is possible in angular 4, but definately in Angular 12 and higher.

It needs however, a reference to the exact same function. Just giving it Validators.required does not work. You need to create a unique reference to it:

requiredValidator = Validators.required;
   
this.form = this._fb.group({
    title: ['', [this.requiredValidator, Validators.minLength(3), Validators.maxLength(50)]],
    description: ['', [this.requiredValidator, Validators.minLength(3)]]
}); 

saveDraft() {
    this.title.removeValidators(this.requiredValidator); 
}

get title(): AbstractControl {
    return this.form.get('title');
}
1
  • This is a better answer to the actual question in modern Angular. Commented Apr 11 at 6:42
6

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); 
1
  • It work for me. It make the form valid when the value of the item is null. Commented Nov 11, 2021 at 17:29
2

To Add Validators:

this.form = this._fb.group({
    title: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
    description: ['', [Validators.required, Validators.minLength(3)]]
});

or

this.form.get('title').setValidators([Validators.required,Validators.minLength(3), Validators.maxLength(50)]);

To Remove the 'Required' validator only, you can reset the validators.

saveDraft() {
     this.form.get('title').setValidators([Validators.minLength(3), Validators.maxLength(50)]);
     this.form.get('title').updateValueAndValidity();
}

updateValueAndValidity determines how the control propagates changes and emits events when the value and validators are changed

1

Unfortunately Angular doesn't have a removeValidator capability at this point in time. All you can do is re-set the validators without the one you want to remove, so you need to know which validators you want to keep rather than which one you want to remove. so this:

this.form.get('title').setValidators([Validators.minLength(3), Validators.maxLength(50)]);

Is the closest you have to a remove function. You can't access the current validators on a formcontrol either to try and write your own remove function. The best you could do is write your own form control validation manager class that can keep track of the validators on a given control and manage them for you.

1
  • I'm here because my control with min/maxlength set still gets required error on an empty field. Commented Feb 13, 2019 at 16:08
1

I had the same problem with saving entry as draft and prepared the following solution:

@Component({
    // ...
})
export class FormComponent{
    form: FormGroup;

    constructor(private fb: FormBuilder){
        this.form = this.fb.group({
            name: ['', Validators.required, Validators.maxLength(20)],
            description: ['', Validators.required, Validators.maxLength(200)],
            address: this.fb.group({
                line1: ['', Validators.required, Validators.maxLength(100)],
                line2: ['', Validators.maxLength(100)]
            })
        });
    }    

    validateDraft(formElement: FormGroup | FormArray | FormControl): boolean {
        let result = true;

        Object.keys(formElement.controls).forEach(field => {
            const control = formElement.get(field);

            if(control instanceof FormControl) {
                control.markAsTouched({ onlySelf: true });

                if(control.errors && control.errors['required']) {
                    control.markAsUntouched({ onlySelf: true });
                }
                else if(control.invalid) {
                    result = false;
                }
            } else if (control instanceof FormArray) {
                if (!this.validateDraft(control)) {
                    result = false;
                } 
            }else if (control instanceof FormGroup) {
                if (!this.validateDraft(control)) {
                    result = false;
                }   
            }
        });
    }

    saveDraft(){
        if(this.validateDraft(this.form)){
            //save draft - ignore required errors
        }
    }

    save(){
        if(this.form.valid){
            //save
        }
    }
}
1
  • this is the best solution for me
    – brijmcq
    Commented Sep 22, 2019 at 11:54
1
this.fromName.get("formControlName").setValidators([Validators.required]);//setting validation
this.fromName.get("formControlName").setErrors({'required':true});//error message
this.fromName.updateValueAndValidity();//update validation


this.fromName.get("formControlName").clearValidators([Validators.required]);//clear validation
this.fromName.get("formControlName").setErrors(null);//updating error message
this.fromName.updateValueAndValidity();//update validation
4
  • While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.
    – Borja
    Commented Sep 2, 2020 at 7:07
  • 2
    clearValidators() doesn't accept arguments, and clears all validators. See angular.io/api/forms/AbstractControl#clearValidators Commented Feb 25, 2021 at 10:40
  • 2
    There are no parameters on clearValidators() . Why people up vote this wrong info..!!! Commented Oct 11, 2021 at 13:47
  • clearValidators() is supposed to clear the entire list of validators, you can't choose and tell what specific validators you want to remove in clearValidators() Commented Oct 12, 2022 at 7:31
1

you can use this to clear validation from reactive form

this.form.controls['title'].clearValidators();
this.form.controls['title'].updateValueAndValidity();

you can use this to add validation in reactive form

this.form.controls['title'].setValidators([Validators.required]);
this.form.controls['title'].updateValueAndValidity();
0

Use empty array to remove all existing validators.

this.frmFeasibility.controls['pop_name'].setValidators([]);
this.frmFeasibility.controls['pop_name'].updateValueAndValidity();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.