Form Validation: Built-In, Custom, Cross-Field and Async
Built-In Validators
typescript
Validators.required
Validators.minLength(3) Validators.maxLength(30)
Validators.min(0) Validators.max(100)
Validators.email
Validators.pattern(/^[A-Za-z ]+$/)
Validators.requiredTrue // checkbox must be ticked
Validators.compose([a, b]) // combine (usually just pass an array)
Custom Validator
A validator is a function that returns null when valid, or an error object when invalid.
typescript
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
// 1. simple validator
export function noSpaces(control: AbstractControl): ValidationErrors | null {
return /\s/.test(control.value ?? '') ? { noSpaces: true } : null;
}
// 2. validator factory with a parameter
export function forbiddenWords(words: string[]): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = (control.value ?? '').toLowerCase();
const found = words.find(w => value.includes(w));
return found ? { forbiddenWords: { word: found } } : null;
};
}
// 3. strong password
export const strongPassword: ValidatorFn = (control) => {
const v: string = control.value ?? '';
const ok = v.length >= 8 && /[A-Z]/.test(v) && /[a-z]/.test(v) && /\d/.test(v);
return ok ? null : { weakPassword: true };
};
typescript
username: ['', [Validators.required, noSpaces, forbiddenWords(['admin', 'root'])]],
password: ['', [Validators.required, strongPassword]],
Cross-Field Validation: Password Match
Put the validator on the group, because it needs two controls.
typescript
export const passwordsMatch: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
const pass = group.get('password')?.value;
const confirm = group.get('confirm')?.value;
return pass && confirm && pass !== confirm ? { passwordMismatch: true } : null;
};
form = this.fb.nonNullable.group(
{ password: ['', strongPassword], confirm: [''] },
{ validators: passwordsMatch });
html
@if (form.hasError('passwordMismatch') && form.controls.confirm.touched) {
<small class="error">Passwords do not match.</small>
}
Async Validator: Is the Username Free?
typescript
import { AsyncValidatorFn } from '@angular/forms';
import { map, catchError, of, timer, switchMap } from 'rxjs';
export function uniqueUsername(http: HttpClient): AsyncValidatorFn {
return (control) => {
if (!control.value) return of(null);
return timer(400).pipe( // debounce
switchMap(() => http.get<{ taken: boolean }>(`/api/users/check`, { params: { name: control.value } })),
map(res => res.taken ? { usernameTaken: true } : null),
catchError(() => of(null))); // do not block the user if the API fails
};
}
username: ['', { validators: Validators.required, asyncValidators: uniqueUsername(this.http), updateOn: 'blur' }]
Status PENDING: While an async validator runs, the control status is
PENDING. Disable the submit button with form.pending as well as form.invalid.
Show Errors Clearly
typescript
const MESSAGES: Record<string, (e: any) => string> = {
required: () => 'This field is required',
email: () => 'Enter a valid email',
minlength: e => `At least ${e.requiredLength} characters`,
weakPassword: () => 'Use 8+ characters with upper, lower case and a number',
usernameTaken: () => 'That username is already taken',
};
export function firstError(control: AbstractControl): string | null {
if (!control.errors || !(control.touched || control.dirty)) return null;
const key = Object.keys(control.errors)[0];
return MESSAGES[key]?.(control.errors[key]) ?? 'Invalid value';
}
| Option | Effect |
|---|---|
updateOn: 'blur' | Validate when the user leaves the field |
updateOn: 'submit' | Validate on submit |
default 'change' | Validate on every keystroke |
Server validation too: Client checks improve usability but can be bypassed. Always validate again on the server and show server errors in the form with
control.setErrors({ server: 'message' }).
Conclusion
A validator returns null or an error object. Put cross-field rules on the group, use async validators with debouncing for server checks and create a helper to display friendly messages.
Quick Summary: ValidatorFn -> null | {error}; group validators for cross-field; async for server checks.

