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:
//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;
};
}
}
How to perform custom validation in Angular forms?
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.
Table of Content
- Custom Validator Functions
- Custom Directive with a Validator