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 use ngFor and ngIf on same element in angular 12 ?

October 23, 2021October 23, 2021

In this tutorial we are going to resolve the issue of using *ngFor and *ngIf on same element. so, in angular ngIf and ngFor is a structural directives, and we can not use two structural directive on same element.ngIf is used for to make conditional logic and ngFor is used…

Read More
Javascript Angular Focusout Event on Input Example

Angular Focusout Event on Input Example

September 24, 2022March 16, 2024

Angular Focusout Event on Input is an Angular event binding it triggers when user interacts with DOM like text based input element and focus get out from the element. Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular FocusOut…

Read More
Softwares disable change detection anagular

How to disable automatic change detection strategy in angular component?

July 4, 2021November 8, 2023

In angular all components by default take the changes as any event occur, but sometime we disable automatic change detection strategy in angular. Thus, to detach the two way binding in component we can use changeDetection strategy in component metadata. Angular Change Detection Strategy is simple to implement using the…

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