Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i add/remove validators conditionally in reactive forms?

I have a reactive form like this

this.form = this.formBuilder.group({
  ...
  email: [],
  receiveNewsletter: [],
  ...
})

I want all fields to be optional, except if user checks receiveNewsletter, the email field should be required. How can i do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to watch the value of the checkbox and add or remove the required validator based on the value of receiveNewsletter

this.form.controls.receiveNewsletter.valueChanges.subscribe(value => {
   if(value){
      this.form.controls.email.addValidators(Validator.required);
   } else {
      this.form.controls.email.removeValidators(Validator.required);
   }
   this.form.controls.email.updateValueAndValidity(); //remember to add this to update the form control state
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading