How to perform custom validation in Angular forms?
Last Updated :
01 May, 2024
Angular's built-in form controls provide a set of predefined validators for common validation such as required fields, email format, and minimum/maximum values. However, there may be cases where you need to implement custom validation logic specific to your application's requirements.
Angular offers several approaches to accomplish this, allowing you to create custom validators and apply them to form controls.
Step 1: Create a new Angular application
ng my-app
Step 2: Once the application is created, navigate to the project directory
cd my-app
Folder Structure:
folder structureDependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.3",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Custom Validator Functions
In this approach, you'll create a standalone validator function that encapsulates your custom validation logic. Here's an example of a validator function that checks if a password meets specific complexity requirements:
Example:
JavaScript
//app.component.ts
import { CommonModule, JsonPipe, NgIf } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { SharedModule } from './shared/shared.module';
import { AbstractControl, FormControl, FormGroup, FormsModule,
ReactiveFormsModule, ValidationErrors,
ValidatorFn, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, NgIf, JsonPipe, SharedModule,
ReactiveFormsModule, FormsModule],
templateUrl: `
<div>
<h2>Password Complexity Validator</h2>
<form [formGroup]="form">
<div>
<label for="password">Password:</label>
<input type="password" id="password" formControlName="password">
<div *ngIf="form.get('password')?.hasError('required')">
Password is required.
</div>
<div *ngIf="form.get('password')?.hasError('passwordComplexity')">
Password must contain at least one uppercase letter,
one lowercase letter, and one number.
</div>
</div>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
</div>
`,
styleUrl: './app.component.css'
})
export class AppComponent {
form = new FormGroup({
password: new FormControl('', [Validators.required,
this.passwordComplexityValidator()])
});
passwordComplexityValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const password = control.value;
const hasUppercase = /[A-Z]+/.test(password);
const hasLowercase = /[a-z]+/.test(password);
const hasNumeric = /[0-9]+/.test(password);
const passwordValid = hasUppercase && hasLowercase && hasNumeric;
return !passwordValid ? { passwordComplexity: true } : null;
};
}
}
Custom Directive with a Validator
In this approach, you'll create a custom directive that implements the Validator interface. This approach is useful when you want to encapsulate the validation logic within a reusable directive that can be applied to multiple form controls.
Generate a new directive using the Angular CLI:
ng generate directive password-complexity
Updated Folder Structure:
folder structureExample: This example implements the Validator interface in the directive with custom validation logic.
JavaScript
//app.component.ts
import { CommonModule, JsonPipe, NgIf } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { SharedModule } from './shared/shared.module';
import {
AbstractControl, FormControl, FormGroup, FormsModule,
ReactiveFormsModule, ValidationErrors, ValidatorFn,
Validators
} from '@angular/forms';
import { PasswordComplexityDirective } from './password-complexity.directive';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, NgIf, JsonPipe, SharedModule,
ReactiveFormsModule, FormsModule, PasswordComplexityDirective],
template: `
<div>
<h2>Password Complexity Validator</h2>
<form [formGroup]="form">
<div>
<label for="password">Password:</label>
<input type="password" id="password"
formControlName="password" appPasswordComplexity>
<div *ngIf="form.get('password')?.invalid && (form.get('password')?
.dirty || form.get('password')?.touched)">
<div *ngIf="form.get('password')?.hasError('required')">
Password is required.
</div>
<div *ngIf="form.get('password')?.hasError('passwordComplexity')">
Password must contain at least one uppercase letter,
one lowercase letter, and one number.
</div>
</div>
</div>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
</div>
`,
styleUrl: './app.component.css'
})
export class AppComponent {
form = new FormGroup({
password: new FormControl('', [
Validators.required
])
});
}
JavaScript
//password-complexity.directive.ts
import { Directive } from '@angular/core';
import {
AbstractControl, NG_VALIDATORS,
ValidationErrors, Validator
} from '@angular/forms';
@Directive({
selector: '[appPasswordComplexity]',
standalone: true,
providers: [
{
provide: NG_VALIDATORS,
useExisting: PasswordComplexityDirective,
multi: true
}
]
})
export class PasswordComplexityDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
const password = control.value;
// Custom validation logic
const hasUppercase = /[A-Z]+/.test(password);
const hasLowercase = /[a-z]+/.test(password);
const hasNumeric = /[0-9]+/.test(password);
const passwordValid = hasUppercase && hasLowercase && hasNumeric;
return !passwordValid ? { passwordComplexity: true } : null;
}
}
Output:

Similar Reads
How to perform form validation in React?
Form validation in React involves ensuring that the data entered into a form meets certain criteria before submission. In this, we will see the form validation in React. Pre-requisitesNodeJS and NPMReactJSReact useState hookHTML, CSS, and JavaScriptSteps to Create React Application And Installing Mo
4 min read
How to validate checkbox form in angular 15
In Angular applications, it is often necessary to validate form inputs to ensure that users provide the required information correctly. Checkbox inputs are commonly used to allow users to select one or more options from a list. This article will cover different approaches to validating checkbox inpu
5 min read
How to trigger Form Validators in Angular2 ?
In Angular 2, the best way to deal with complex forms is by using Reactive forms. Below we are going to elaborate on how to trigger form validators for login page. In reactive forms, we use FormControl and by using this, we get access to sub-fields of form and their properties. Some of their propert
4 min read
How to Add Form Validation In Next.js ?
Forms play a crucial role in modern web applications by ensuring the accuracy and validity of data. NeÂxt.js, a versatile framework for building ReÂact applications, offers form validation that helps verify useÂr input against predefined criteÂria, provides immediate feedback, and enhances data qual
3 min read
How to Implement Angular Forms?
Creating a Form in Angular includes the use of directives such as ngSubmit and ngModel. We will be using a functional component to render the elements. Various HTML elements are created in the project. To implement the project we will create the styling using CSS. Prerequisites:Functional Components
4 min read
How to Validate Data in AngularJS ?
In this article, we will know to validate the data in Angular JS, along with understanding the various ways to validate the data through the examples. AngularJS allows client-side form validation. Form validation is necessary because it ensures that the data in the form is correct, complete, and are
10 min read
AngularJS Form Validation
AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not. Form input fi
3 min read
How to prevent form submission when input validation fails in AngularJS ?
Validation of fields is an important process while developing a dynamic web application. In terms of security, validation is an important concept. We pass the data from the client side through input fields to the server. If any of the fields is not validated properly and the user sends any irrelevan
7 min read
How to add validation to ngbDropdownMenu in Angular ?
Angular is one of the popular JavaScript libraries that allows web developers to develop dynamic and interactive single-page applications. There are different components that are used in the user interfaces to provide functionality in the application. One of the components is the Dropdown Menus, whi
8 min read
How to add Buttons without Submit the Form in Angular?
In Angular, when adding buttons to a form, their default behavior on click is to submit the form itself. However, there are certain situations in which it is necessary to create buttons for forms that provide some sort of functionality or trigger custom logic without triggering the default form subm
5 min read