JavaScript

Dynamically add/remove validators in angular 12+

Share your learning

Today we are going to discuss how we can dynamically add/remove validators in angular. Angular dynamic validators are required when our form fields depend on each other.

For example, 

We have a user form where we can fill the user information like name, email and account type. If the account type is selected as the primary account then users need to fill the security code also.

I assume that you are already familiar with angular installation and project setup. So, without extra ado let’s get straight to the point.

The html file form.component.html

<form [formGroup]="userform" (ngSubmit)="submit()">
   <div class="row">
       <div class="col-12 my-2">
           <input class="form-control" type="text" placeholder="Enter your name" formControlName="name">
 
           <p class="text-danger" *ngIf="userform.controls['name'].touched && userform.controls['name'].hasError('required')">Please enter the name!</p>
       </div>
       <div class="col-12 my-2">
           <input class="form-control" type="email" placeholder="Enter your email" formControlName="email">
 
           <p class="text-danger" *ngIf="userform.controls['email'].touched && userform.controls['email'].hasError('required')">Please enter the email!</p>
       </div>
       <mat-form-field appearance="fill">
           <mat-label>Account type</mat-label>
           <mat-select formControlName="account_type">
               <mat-option value="primary">Primary</mat-option>
               <mat-option value="secondary">Secondary</mat-option>
               <mat-option value="other">Others</mat-option>
           </mat-select>
           <p class="text-danger" *ngIf="userform.controls['account_type'].touched && userform.controls['account_type'].hasError('required')">Please select the account type!</p>
       </mat-form-field>
 
       <div class="col-12 my-2" *ngIf="primary_account">
           <input class="form-control" type="text" placeholder="Enter your code" formControlName="security">
 
           <p class="text-danger" *ngIf="userform.controls['security'].touched && userform.controls['security'].hasError('required')">Please enter the Security code!</p>
       </div>
   </div>
   <div class="text-left my-2">
       <button class="btn btn-primary" type="submit" [disabled]="!userform.valid">Submit</button>
   </div>
</form>

The typescript file form.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
 
@Component({
 selector: 'app-form',
 templateUrl: './form.component.html',
 styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
 userform: FormGroup;
 primary_account: boolean = false;
 
 constructor(
   private formBuilder: FormBuilder
 ) {
   this.userform = this.formBuilder.group({
     name: new FormControl('', [Validators.required]),
     email: new FormControl('', [Validators.required, Validators.email]),
     account_type: new FormControl('', [Validators.required]),
     security: new FormControl('')
   })
 }
 
 ngOnInit(): void {
   this.userform.get('account_type')?.valueChanges.subscribe((type) => {
     this.primary_account = type == 'primary';
     if (this.primary_account) {
       this.userform.get('security')?.addValidators([Validators.required])
     } else {
       this.userform.get('security')?.removeValidators([Validators.required])
     }
    
     this.userform.get('security')?.updateValueAndValidity();
   })
 }
 
 submit() {
   console.table(this.userform.value)
 }
 
}

Example output

  1. When user fill all the required fields and account type is secondary so, we don’t need security code.

2. When user fill all the required fields but account type is primary so, so we need security code also.

3. Finally, When user doesn’t fill any of the required fields.

Hope you find this quick tip useful. See you in the next article.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago