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

How to make a reactive form in angular?

August 29, 2021September 10, 2021

Angular has vast library of modules so reactive form is one of the part of angular library. Prerequisites knowledge: Angular HTML CSS Javascript So, let’s start building a from . Steps to create a reactive form in angular Create a new or existing angular project, you can also read this…

Read More
Javascript get radio input value in jQuery

How to get radio input value in jQuery ?

October 31, 2021November 5, 2023

While submitting a form or validating a form using the jQuery, we can get all the values of form easily but radio button works differently and we need some extra efforts to fetch the value of radio input. So in this article i will demonstrate to fetch the value of…

Read More
Javascript Customdirective in angular

How to Create Custom Directive in Angular 12?

October 12, 2021February 8, 2024

In this tutorial we will learn to create the custom directive in angular and how to use them in our project. Custom directives are those directives by which we can enhance the html capabilities and can bind custom attributes, methods to it. We can reuse them in any element or…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version