set validation on angular reactive form at runtime

In Angular, you can set validation on a reactive form at runtime by using the setValidators method on the form control. For example, if you have a form control named “email” and you want to set a required validation on it at runtime, you can use the following code:

this.form.get('email').setValidators([Validators.required]);

You can also set multiple validators on a form control by passing an array of validator functions to the setValidators method. For example, to set both required and email validation on the “email” control, you can use the following code.

this.form.get('email').setValidators([Validators.required, Validators.email]);

You can also remove the validators by using clearValidators().

this.form.get('email').clearValidators();

You should also call updateValueAndValidity() after setting or clearing the validators to update the form control’s status.

this.form.get('email').updateValueAndValidity();

It’s important to note that you need to import the Validators module for this to work.

import { FormControl, FormGroup, Validators } from '@angular/forms';
import { FormControl, FormGroup, Validators } from '@angular/forms';

//setting th validation
this.form.get('email').setValidators([Validators.required]);
this.form.get('email').updateValueAndValidity();

// clearing the validation
this.form.get('email').clearValidators();
this.form.get('email').updateValueAndValidity();

If dynamic removal or Addition of validation is not working with above approach, then you can try below approach.

//setting th validation
this.form.get('email').setValidators([Validators.required]);
this.form.get('email').updateValueAndValidity({onlySelf:true});

// clearing the validation
this.form.get('email').setValidators(null);
this.form.get('email').setErrors(null);
this.form.get('email').updateValueAndValidity({onlySelf:true});
this.form.get('email').setValidators(null);
this.form.get('email').setErrors(null);
this.form.get('email').updateValueAndValidity();

Leave a Reply