Quantcast
Channel: Infragistics Community
Viewing all articles
Browse latest Browse all 2374

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

$
0
0

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:

ngOnInit() {
    this.loginForm = this.fb.group({
      email: [null, Validators.required],
      password: [null, [Validators.required, Validators.maxLength(8)]],
      phonenumber: [null]
    });

  }

 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.

<form (ngSubmit)='loginUser()' [formGroup]='loginForm' novalidate class="form">     <input formControlName='email' type="text" class="form-control" placeholder="Enter Email" />     <div class="alert  alert-danger" *ngIf="loginForm.get('email').hasError('required') && loginForm.get('email').touched">         Email is required
     </div>     <input formControlName='password' type="password" class="form-control" placeholder="Enter Password" />     <input formControlName='phonenumber' type="text" class="form-control" placeholder="Enter Phone Number" />     <div class="alert  alert-danger" *ngIf="loginForm.get('phonenumber').hasError('required') && loginForm.get('phonenumber').touched">         Phone Number is required
     </div>     <br />     <button [disabled]='loginForm.invalid' class="btn btn-default">Login</button> </form>

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:

loginUser() {
    console.log(this.loginForm.status);
    console.log(this.loginForm.value);
}

 

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 :

this.loginForm = this.fb.group({
    email: [null, Validators.required],
    password: [null, [Validators.required, Validators.maxLength(8)]],
    phonenumber: [null],
    notification: ['email']
});

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

<form (ngSubmit)='loginUser()' [formGroup]='loginForm' novalidate class="form">    <input formControlName='email' type="text" class="form-control" placeholder="Enter Email" />    <div class="alert  alert-danger" *ngIf="loginForm.get('email').hasError('required') && loginForm.get('email').touched">        Email is required
    </div>    <input formControlName='password' type="password" class="form-control" placeholder="Enter Password" />    <input formControlName='phonenumber' type="text" class="form-control" placeholder="Enter Phone Number" />    <div class="alert  alert-danger" *ngIf="loginForm.get('phonenumber').hasError('required') && loginForm.get('phonenumber').touched">        Phone Number is required
    </div>    <br />    <label class='control-label'>Send Notification</label>    <br />    <label class="radio-inline">        <input type="radio" value="email" formControlName="notification">Email
    </label>    <label class="radio-inline">        <input type="radio" value="phone" formControlName="notification">Phone
    </label>    <br />    <button [disabled]='loginForm.invalid' class="btn btn-default">Login</button></form>

At this point form, looks like below:

Subscribe to valueChanges

In Reactive forms both FormControls and FormGroups has a valueChanges method. It returns an observable type, so you can subscribe to it, to work with real-time value changing of FormControls or FormGroups.

In our example, we need to subscribe to valueChanges of notification FormControl. This can be done as below:

formControlValueChanged() {
    this.loginForm.get('notification').valueChanges.subscribe(
        (mode: string) => {
            console.log(mode);
        });
}

We need to call this an OnInit lifecycle hook a shown below:

ngOnInit() {
    this.loginForm = this.fb.group({
        email: [null, Validators.required],
        password: [null, [Validators.required, Validators.maxLength(8)]],
        phonenumber: [null],
        notification: ['email']
    });

    this.formControlValueChanged();

}

Now when you change the selection for notification on the form in the browser console you can see, you have most recent value.

Keep in mind that, we are not handling any event on the radio button to get the latest value. Angular has a valueChanges method which returns recent value as observable on the FormControl and FormGroup, and we are subscribed to that for recent value on notification FormControl.

Conditional Validation

Our requirement is that when notification is set to phone then phonenumber FormControl should be required field and if it is set to email then phonenumber FormControl should not have any validation.

Let us modify formControlValueChnaged() function as shown in the next listing to enable conditional validation on phonenumber FormControl.

formControlValueChanged() {
    
    const phoneControl = this.loginForm.get('phonenumber');
    this.loginForm.get('notification').valueChanges.subscribe(
        (mode: string) => {
            console.log(mode);
            if (mode === 'phone') {
                phoneControl.setValidators([Validators.required]);
            }
            else if (mode === 'email') {
                phoneControl.clearValidators();
            }
            phoneControl.updateValueAndValidity();
        });

}

 

There are a lot of codes above, so talk through line by line.  

  1. Using get method of FormBuilder getting an instance of phone number FormControl
  2. Subscribing to the valueChanges method on notification FormControl
  3. Checking the current value of notification FormControl
  4. If the current value is phone, using setValidators method of FormControl to set required validator on phonenumber control
  5. If the current value is email, using clearValidators method of FormControl to clear all validation on phonenumber control
  6. In last calling updateValueAndValidity method to update validation rules of phonecontrol

Run the application and you will see that as you change notification value, validation of phonenumber is getting changed,

 By using the power of Angular Reactive Form’s valueChanges method, you can achieve conditional validations and many other functionalities such as reacting to changes in the underlying data model of the reactive form.

Like this post?

If you like this post, please share it. In addition, if you haven’t checked out Infragistics Ignite UI for Angular Components, be sure to do so! They’ve got 30+ material based Angular components to help you code speedy web apps faster


Viewing all articles
Browse latest Browse all 2374

Trending Articles