Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
custom validation in angular reactive form

How to make custom validation in angular reactive form ?

Aman Jain, September 7, 2021October 1, 2021

Angular already have many built-in validators but sometimes we need some extra validation according to our project need.

Steps to create custom validators

Step 1: Create a function or class method where we can define our all custom validators.

File: src/CustomValidators.ts

import { AbstractControl, ValidatorFn, FormControl } from '@angular/forms';
  
 
export class CustomValidators 
  
  constructor() {}
 
}

2. Define the function definition of custom validators to validate only char in input field

import { AbstractControl, ValidatorFn, FormControl } from '@angular/forms';
  
 
export class CustomValidators{
  
  constructor() {}

  static onlyChar():ValidatorFn{
    return (control: AbstractControl): { [key: string]: boolean } | null => {
     
      if(control.value=="")
        return null;

      let re = new RegExp("^[a-zA-Z ]*$"); 
      if (re.test(control.value )) {
        return null;
      } else {
        return { "onlyChar": true };
      }
      
    }

  }
}

I have defined a function name onlyChar and return type is ValidatorFn, so in the definition of function i returned a inline function which accepts one parameter type of AbstractControl.

In the next expression, i a checking the value of control if its empty then i am returning null, which means no error in the control.

In next step i have defined RegExp to validate the input for Capital and lower case char only, which return onlyChar .

Let’s implement it in our FormGroup Form with validation.

  • register.component.ts
  • register.component.html
register.component.ts
import { Component, OnInit } from '@angular/core';
import {  FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './<meta charset="utf-8">register.component.html',
  styleUrls: ['./<meta charset="utf-8">register.component.css']
})
export class RegisterComponent implements OnInit {
 
  form: FormGroup = new FormGroup(
      {
        name:new FormControl("",[Validators.required,Validators.minLength(4),CustomValidators.onlyChar()]),
        email:new FormControl("",[Validators.required,Validators.email]),
        password:new FormControl("",[Validators.required]),
        
      }
    );
  constructor() { }

  ngOnInit(): void {

     
  }

  submitForm(){
    if(this.form.valid){
      console.log("send request to server",this.form.value);
// send request to server

    } 
    else{
      this.form.markAllAsTouched();
      console.log("Form has errors");
    }
  }

}
register.component.html
<form [formGroup]="form" (submit)="submitForm()">
    <div>
       
        Name : <input type="name" formControlName="name" placeholder="Name" /> <br>
        <div *ngIf="form.controls.name.invalid && (form.controls.name.dirty || form.controls.name.touched)"
            class="alert alert-danger">

            <div *ngIf="form.controls.name.errors?.required">
                Name is required.
            </div>
            <div *ngIf="form.controls.name.errors?.minlength">
                Name must be at least 4 characters long.
            </div>
<div *ngIf="form.controls.name.errors?.onlyChar">
                Name only contain characters.
            </div>

        </div>
    </div>
    <div>
        Email : <input type="email" formControlName="email" placeholder="Email" /> <br>
        <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>
    </div>
    <div>
        Password : <input type="password" formControlName="password" placeholder="Password" /> <br>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>

</form>

Output:
Angular custom validator
Check this example and code for custom validation

Related

Javascript Angular

Post navigation

Previous post
Next post

Related Posts

Javascript Laravel Multi Select Tag Autocomplete Using Select2

Laravel Multi Select Tag Autocomplete Using Select2

July 19, 2022July 19, 2022

In this article we will learn to use Laravel Multi Select Tag Autocomplete Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. In this article we will cover multiple…

Read More
Javascript Password and confirm password validation in javascript

Password and confirm password validation in javascript

September 17, 2021November 21, 2021

In this tutorial, we will cover password strength validation , password not empty validation and confirm password validation. we will check on every submission of form whether the entered password pass or fail the criteria. Password Strength validation in javascript Password field must contain At least 8 characters Should be…

Read More
Javascript Angular Blur Event on Input Example

Angular Blur Event on Input Example

September 29, 2022March 16, 2024

Angular Blur Event on Input is an Angular event binding it triggers when user removes the focus from the input element. Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular Blur Event on Input with Example. In core javascript…

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