Custom validators help you check if form inputs follow your own rules. They make sure users enter data correctly beyond built-in checks.
0
0
Custom validators in Angular
Introduction
You want to check if a password has special characters.
You need to verify a username is unique.
You want to confirm two password fields match.
You want to validate a date is in the future.
You want to block certain words in a text input.
Syntax
Angular
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export function customValidator(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const value = control.value; // Your validation logic here const isValid = /* condition */; return isValid ? null : { customError: true }; }; }
A custom validator is a function that returns another function.
The inner function checks the control's value and returns null if valid or an error object if invalid.
Examples
This validator checks if the input contains spaces and returns an error if it does.
Angular
export function noSpaceValidator(): ValidatorFn { return (control: AbstractControl) => { const hasSpace = (control.value || '').includes(' '); return hasSpace ? { noSpace: true } : null; }; }
This validator checks if the input length is at least a minimum number.
Angular
export function minLengthValidator(min: number): ValidatorFn { return (control: AbstractControl) => { const length = (control.value || '').length; return length >= min ? null : { minLength: { requiredLength: min, actualLength: length } }; }; }
Sample Program
This Angular component uses a custom validator to block the word 'forbidden' in the input. If the user types it, an error message shows below the input.
Angular
import { Component } from '@angular/core'; import { FormControl, ValidatorFn } from '@angular/forms'; // Custom validator to block the word 'forbidden' export function forbiddenWordValidator(): ValidatorFn { return (control) => { const forbidden = (control.value || '').toLowerCase().includes('forbidden'); return forbidden ? { forbiddenWord: true } : null; }; } @Component({ selector: 'app-root', standalone: true, template: ` <label for="input">Enter text:</label> <input id="input" [formControl]="textControl" aria-describedby="error" /> <div *ngIf="textControl.errors?.forbiddenWord" id="error" role="alert" style="color: red;"> The word 'forbidden' is not allowed. </div> ` }) export class AppComponent { textControl = new FormControl('', [forbiddenWordValidator()]); }
OutputSuccess
Important Notes
Always return null when the input is valid.
Use descriptive error keys in the returned object to identify the error.
Combine custom validators with built-in ones by passing them in an array.
Summary
Custom validators let you add your own rules to form inputs.
They return null if valid or an error object if invalid.
Use them to improve user input quality and app reliability.