Member-only story
Dynamically Add/Remove Validators in Angular Reactive Forms
A simple guide to adding and removing dynamic validations in Angular reactive forms

If you’re developing an Angular application, you might face a situation where you have to add or remove some validators dynamically in form controls. For example, let’s suppose you have a County
field in your reactive form and you want to make it required based on the country selected by the user. For this, you might think of adding and removing the Required
validator from the County
field based on the country selected.
Well, for this kind of scenario, Angular helps us a lot. We have some built-in functions in Angular which we can use to set validators conditionally — and thanks to reactive forms, which allows us to do so very, very easily.
So let’s just start from the beginning.
I’m expecting that you have a running Angular application with reactive forms. For me, I have a very simple form with two fields. One is for Country
and the second one is for County
, as mentioned in the beginning.
I have a template and corresponding component code as shown below.
Let’s discuss what we are doing here, step by step.
- We just created a simple reactive Form with two fields,
Country
andCounty
. - We have a drop-down for
Country
and whenever the drop-down value is changed, we are calling a function which isonCountryChange()
to update the validator(s) forCounty
. - Just to verify if the
Required
validator is set, we are checking ifCounty
field hasrequired
error or not. - We simply initialized the reactive form with default validation.