Reactive Forms and Validation — Part 2
Adjusting validation rule at run time
This is in continuation of my previous blog of validation with reactive forms.
One of the advantage of using validation in reactive form is the ability to easily adjust validation at run time or on the fly.
I have added one more field named phone in user interface and two radio buttons. based on the selection of radio button by user, we need to make required field either phone or email.
There are three methods in Validator class named **setValidators, clearValidators and updateValueAndValidity** that can help us to adjust validation at run time.
myElement.setValidators(Validators.required)— you can set validation rule at run time.
myElement.clearValidators() — You can clear/remove validation at run time.
myElement.updateValueAndValidity() — Changing validation rule at run time does not cause reevaluation. if we want to reevaluate it then we have to call this method.
We have made following changes in component file. User can select notification option either email or text. If he selects email then he will be notified via email else via text.
Let us make required changes in template and component file.
First We get reference of phone no FormControl and checking the value. If user selects phone, we are setting required validators for phone no else clear validators. updateValueAndValidity causes re-evaluation of phone no element.
below is the output after adding validators at run time. We now have validation rule that adjust at run time. if we select text then validation error message is displayed and save button become disable.