Form Validation and Custom Validators
Validation is what turns a form from a collection of inputs into a trustworthy data-entry surface. In Angular's reactive forms, every FormControl carries a validator function (or array of functions) that Angular re-runs on every value change, producing a live ValidationErrors object (or null when valid) that the template can read via properties like invalid, touched, and dirty. Angular ships a set of built-in validators — Validators.required, Validators.minLength, Validators.maxLength, Validators.pattern, Validators.email, Validators.min, and Validators.max — that cover the vast majority of simple field-level checks. Beyond those, real applications almost always need custom logic: password strength rules, matching-field checks, uniqueness checks against a server, or business rules that only make sense for your domain. Angular lets you write these as plain functions with no special decorators, which makes them easy to unit test in isolation from any component or DOM.
Cricket analogy: Validators are like a third umpire re-checking every delivery against the rules the instant it's bowled, flagging a no-ball or wide immediately, while Angular's built-ins like Validators.required cover standard rules like a legal delivery, leaving custom rules like DRS review protocols to be written for your specific tournament.
Writing a synchronous custom validator
A validator is simply a function matching the ValidatorFn signature: it takes an AbstractControl and returns either null (valid) or a ValidationErrors object whose keys become the error codes you check in the template. Because validators are plain functions, you can parameterize them with a factory: a function that accepts configuration and returns a ValidatorFn closing over that configuration. This pattern is how Validators.minLength itself is implemented internally, and it is the idiomatic way to build reusable, configurable validation logic across a codebase.
Cricket analogy: A ValidatorFn is like a bowling machine set to a specific configuration (speed, spin), where the factory function is the control panel letting you dial in different settings and produce a reusable machine preset for any net session.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
// Factory that returns a configurable ValidatorFn
export function forbiddenWordsValidator(forbidden: string[]): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = (control.value ?? '') as string;
const hit = forbidden.find(word =>
value.toLowerCase().includes(word.toLowerCase())
);
return hit ? { forbiddenWord: { word: hit } } : null;
};
}
// Usage in a reactive form
import { FormControl, Validators } from '@angular/forms';
const bio = new FormControl('', [
Validators.required,
Validators.maxLength(280),
forbiddenWordsValidator(['spam', 'crypto']),
]);Cross-field validation on FormGroup
Some rules span multiple controls — confirming a password, ensuring an end date is after a start date, or requiring at least one checkbox in a group to be checked. These validators are attached to the parent FormGroup (or FormArray) rather than to a single control, because only the group has access to all the sibling values it needs to compare. The convention is to surface the resulting error on the group itself, and read it in the template with formGroup.hasError('mismatch') rather than trying to attach it to either individual control, since neither control is 'wrong' in isolation.
Cricket analogy: A cross-field validator on the FormGroup is like a run-out decision that depends on both the batsman's position and the fielder's throw together, so the umpire attaches the ruling to the whole play, not blaming either player individually.
function passwordsMatchValidator(group: AbstractControl): ValidationErrors | null {
const pass = group.get('password')?.value;
const confirm = group.get('confirmPassword')?.value;
return pass && confirm && pass !== confirm ? { mismatch: true } : null;
}
const form = new FormGroup(
{
password: new FormControl('', Validators.required),
confirmPassword: new FormControl('', Validators.required),
},
{ validators: passwordsMatchValidator }
);Async validators for server-side checks
When a rule can only be verified by asking a server — is this username already taken? — Angular supports async validators with the AsyncValidatorFn signature, which returns an Observable<ValidationErrors | null> or a Promise instead of a synchronous value. Angular automatically debounces re-evaluation by waiting for the previous async validation to settle, but you should still add your own debounceTime and distinctUntilChanged inside the validator when it wraps an HTTP call, otherwise every keystroke can trigger a network request. While an async validator is pending, the control's status is PENDING, which you can use to show a spinner and disable the submit button until validation resolves.
Cricket analogy: An async validator is like waiting on a third-party review from the match referee before confirming a boundary, and just as you wouldn't send a review request on every single ball, the validator debounces so it only asks after the batsman settles on a call.
Compare to Vue and React: Angular's validators are a first-class part of the forms API with a dedicated ValidationErrors contract and PENDING status, whereas React and Vue typically delegate validation entirely to third-party libraries (Formik/Yup, React Hook Form, VeeValidate) because neither framework ships an opinionated forms module of its own.
A common pitfall is forgetting that Validators.required only checks for empty/null/undefined — a string of only whitespace (' ') passes it. If leading/trailing whitespace matters to your domain, pair it with a custom validator or trim the value before validation.
- Built-in validators (required, minLength, pattern, email, etc.) cover common field-level rules out of the box.
- Custom validators are plain functions matching ValidatorFn; use a factory function to make them configurable.
- Cross-field rules (like password confirmation) belong on the parent FormGroup, not on individual controls.
- Async validators return an Observable or Promise and put the control into a PENDING status while resolving.
- Always debounce async validators that call an API to avoid firing a request on every keystroke.
- Read validation state in templates via control.invalid, control.touched, and control.hasError('code').
Practice what you learned
1. What does a synchronous ValidatorFn return when the control is valid?
2. Where should a 'passwords must match' validator be attached?
3. What control status indicates an async validator is still running?
4. Why should async validators that call an API include debounceTime?
5. What is a common gap when relying only on Validators.required for a text field?
Was this page helpful?
You May Also Like
Reactive Forms Basics
Learn Angular's reactive forms approach, where the form model is constructed explicitly in TypeScript with FormControl, FormGroup, and FormBuilder for more predictable, testable forms.
Dynamic and Nested Form Groups
Build complex forms by nesting FormGroups and using FormArray to add, remove, and validate repeating or conditional sets of controls at runtime.
Template-Driven Forms
Explore Angular's template-driven forms approach, where form structure and validation rules live mostly in the HTML template using directives like ngModel and ngForm.
RxJS Operators for HTTP (map, switchMap, catchError)
Master the core RxJS operators — map, switchMap, catchError, and their flattening cousins — used to transform, chain, and recover from HTTP requests.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics