How to do Conditional Validation on valueChanges method in Angular Reactive Forms

Read full article on the Infragistics blog

In this blog post, we will learn to use Angular Reactive Forms value change detection and enable conditional validation on basis of that.

Learn How to Create Your First Angular Reactive Form here

Let us say you have a Reactive Form created using FormBuilder class as shown below:

You have created loginForm, which has three controls: email, password, and phonenumber. Here, you are using FormBuilder to create a reactive form. On the component template, you can attach loginForm as shown in the code listing below. Using property binding, the formGroup property of the HTML form element is set to loginForm and the formControlName value of these controls are set to the individual FormControl property of FormBuilder.

We have also put error messages for email and phone number fields. Besides, that submit button would only be enabled when the form is valid.  Form submit is handled as shown in the listing below:

If the form is valid in browser console, you will get the output as below:

In addition, if there is an error, submit button would be disabled and an error message will be shown as below:

You can learn to create Custom Validators for Angular Reactive Forms here

Now assume a scenario that you have a radio button to send a notification. The user should able to select the send notification option, and on basis of that, certain FormControl will have some validation.

Consider the form below,

We have added a Send Notification option. If the user selects Phone to send notification then Phone Number field should be required, otherwise, it should not be. To achieve this we need to perform following tasks,

  1. Listening to changes
  2. Put conditional validation

To start with, let us modify our form to handle the notification. So now form has a notification FormControl with the default value set to null as shown in the listing below :

On the Reactive form template, we will add radio button group to handle Send Notification option.

Continue Reading full article on the Infragistics blog here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s