Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Dynamically add/remove validators

I have a FormGroup defined like below:

this.businessFormGroup: this.fb.group({
    'businessType': ['', Validators.required],
    'description': ['', Validators.compose([Validators.required, Validators.maxLength(200)])],
    'income': ['']
  })

Now when businessType is Other , I want to remove Validators.required validator from description. And if businessType is not Other, I want to add back the Validators.required.

I am using the below code to dynamically add/remove the Validators.required. However, it clears the existing Validators.maxLength validator.

if(this.businessFormGroup.get('businessType').value !== 'Other'){
    this.businessFormGroup.get('description').validator = <any>Validators.compose([Validators.required]);               
} else {                
    this.businessFormGroup.get('description').clearValidators();               
}

this.businessFormGroup.get('description').updateValueAndValidity(); 

My question is, how can I retain the existing validators when adding/removing the required validator.

like image 250
A J Qarshi Avatar asked Mar 02 '18 18:03

A J Qarshi


People also ask

How do you set a validator dynamically?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.

Which method is used to add dynamic validation to the forms in angular?

Dynamically Add Validators We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.

How do I remove a validator from reactive form?

1. setValidators() method removes all the previous/default validators from form control. For example, let's suppose during form initialization, you set maxLength and minLength validators for County . But once setValidators([Validators.

How do I remove a validator?

Either first use “clearValidators()” to remove all validators and then use “setValidators()” to set needed validation. Or directly use “setValidators()” with the needed validators only (without the validator you don't want to have). That's it for this article. Hope it will be useful for you guys.


3 Answers

This one work for me

onAddValidationClick(){
    this.formGroup.controls["firstName"].setValidators(Validators.required);
    this.formGroup.controls["firstName"].updateValueAndValidity();
}

onRemoveValidationClick(){
    this.formGroup.controls["firstName"].clearValidators();
    this.formGroup.controls["firstName"].updateValueAndValidity();
}
like image 33
San Jaisy Avatar answered Oct 22 '22 12:10

San Jaisy


If you are using Angular 12.2 or higher, you can use the AbstractControl methods addValidators, removeValidators, and hasValidator, as per the docs:

if(this.businessFormGroup.get('businessType').value !== 'Other'){
    this.businessFormGroup.get('description').addValidators(Validators.required);               
} else {                
    this.businessFormGroup.get('description').clearValidators();               
}

For older versions, Angular forms have a built in function setValidators() that enables programmatic assignment of Validators. However, this will overwrite your validators.

For your example you can do:

if(this.businessFormGroup.get('businessType').value !== 'Other'){
    this.businessFormGroup.controls['description'].setValidators([Validators.required, Validators.maxLength(200)]);              
} else {                
    this.businessFormGroup.controls['description'].setValidators([Validators.maxLength(200)]);               
}
this.businessFormGroup.controls['description'].updateValueAndValidity();

It is important to keep in mind that by using this method you will overwrite your existing validators so you will need to include all the validators you need/want for the control that you are resetting.

like image 172
Narm Avatar answered Oct 22 '22 12:10

Narm


If you change the "validator required" more than one time (for example, using a checkbox) you should add this:

this.formGroup.controls["firstName"].setErrors(null);

So:

  onAddValidationClick(){
         this.formGroup.controls["firstName"].setValidators(Validators.required);
        this.formGroup.controls["firstName"].updateValueAndValidity();
      }

onRemoveValidationClick(){
         this.formGroup.controls["firstName"].setErrors(null);
         this.formGroup.controls["firstName"].clearValidators();
        this.formGroup.controls["firstName"].updateValueAndValidity();
      }
like image 21
Kike Lebowski Avatar answered Oct 22 '22 12:10

Kike Lebowski