Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Angular conditional validation in reactive forms

Angular conditional validation in reactive forms

Aman Jain, September 26, 2022March 16, 2024

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.

Two methods for Angular conditional validation in reactive forms

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>
 

Related

Javascript Angular angularconditionalformreactivevalidation

Post navigation

Previous post
Next post

Related Posts

Angular angular file upload

How to upload files with form data in angular 12?

June 20, 2021November 8, 2023

in this tutorial we will learn to upload files with form data in angular. it’s not easy to upload the files along with form data in angular in compare to JQuery and other JavaScript framework. Angular upload a form in JSON and some time it get difficult to obtain the…

Read More

How many type of methods in Restful api?

August 28, 2021February 22, 2024

Restful api is very useful today while creating a mobile application or web application. Restful api or Http request methods There is 4 types of method of http request. Post Get Put Delete Patch 1. Post method Post method is widely used to fetch the content of a form or…

Read More
Javascript How to show html string in angular template

How to show html string in angular template ?

March 31, 2022March 31, 2022

Angular built-in supports vulnerabilities and attacks in a web application like cross site scripting, however sometimes in our application we want to render the html string through bypassing the security of angular. To bypass the security, angular itself provides some methods and directives by which we can render or show…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version