Spread the love

This post covers the basis of angular conditional validation in reactive forms. By the end of this post, the reader will know how to set up a simple form and validate it according to different criteria.

Conditional validation is when the validity of a form control is determined by something other than its value. For example, you might have a form control that is only required if another form control has a certain value.

Angular provides two ways to do conditional validation:

The first way is to set the validators dynamically using setValidators(). This is the recommended way because it gives you more control over the form and is more maintainable in the long run.

The second way is to use the built-in validators. Angular provides a number of built-in validators, such as required and minLength. These can be used directly in the template.


The following example shows how to do angular conditional validation in reactive forms using the setValidators method. In this example, the email field is only required if the checkbox is checked. this example will work in all angular version including angular 2, angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application

Step 1 : Create an angular app

First step is to setup an angular app using below command

ng new example-app

Step 2: Create a Component

Create a component and a method

ng g c hello-world
import { Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  AbstractControlOptions,
  FormBuilder,
  FormGroup,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css'],
})
export class HelloWorldComponent implements OnInit {
  
  form: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      is_email_required: [''],
      email: [
        '',
        [Validators.required, Validators.minLength(5), Validators.email],
      ],
    });
    this.form.get('is_email_required').valueChanges
    .subscribe(value => {
      if(value) {
        this.form.get('email').setValidators(Validators.required)
      } else {
        this.form.get('email').clearValidators();
      }
      this.form.get('email').updateValueAndValidity();

    });
  }

  onSubmit() {
    if (this.form.valid) {
    }
    console.log(this.form.value);
  }
}

Here we used form control valueChanges method to subscribe for each changes so that we can dynamically change the validation

this.form.get('is_email_required').valueChanges
    .subscribe(value => {
      if(value) {
        this.form.get('email').setValidators(Validators.required)
      } else {
        this.form.get('email').clearValidators();
      }
    });

Step 3 : Create template and add html

Now, add simple html template with reactive form input field

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div>
    Is email Required
    <input formControlName="is_email_required" type="checkbox" />
  </div>
  <div>Email: <input formControlName="email" type="email" /></div>
  <div
    *ngIf="
      form.controls.email.invalid &&
      (form.controls.email.dirty || form.controls.email.touched)
    "
    class="alert alert-danger"
  >
    <div *ngIf="form.controls.email.errors?.required">Email is required.</div>
    <div *ngIf="form.controls.email.errors?.email">Enter valid email</div>
  </div>
  <button type="submit">Submit</button>
</form>
 

Leave a Reply