Form Validation
Validation keeps bad data out and tells users how to fix their input. In Angular a validator is a function that receives a control and returns either null (valid) or an errors object such as { required: true } or { minlength: { requiredLength: 8, actualLength: 5 } }.
Built-in validators
| Validator | Error key | Fails when |
|---|---|---|
Validators.required |
required |
Empty value |
Validators.requiredTrue |
required |
Checkbox not checked |
Validators.minLength(n) / maxLength(n) |
minlength / maxlength |
Text too short / long |
Validators.min(n) / max(n) |
min / max |
Number out of range |
Validators.email |
email |
Not an email address |
Validators.pattern(re) |
pattern |
Value doesn't match the regex |
Showing error messages
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-password-form',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<label>Password <input type="password" formControlName="password" /></label>
@let pw = form.controls.password;
@if (pw.touched && pw.errors; as e) {
@if (e['required']) { <p class="err">Password is required.</p> }
@if (e['minlength']; as m) {
<p class="err">At least {{ m.requiredLength }} characters ({{ m.actualLength }} so far).</p>
}
@if (e['pattern']) { <p class="err">Include at least one digit.</p> }
}
</form>
`,
styles: `.err { color: #dd0031; margin: 4px 0; font-size: 14px; }`,
})
export class PasswordForm {
form = inject(FormBuilder).nonNullable.group({
password: ['angul', [Validators.required, Validators.minLength(8), Validators.pattern(/\d/)]],
});
}Multiple validators can fail at once; the errors object contains one key per failure.
Custom validators
A custom validator is just a function with the ValidatorFn signature. A factory function lets you configure it:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenWords(words: string[]): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = String(control.value ?? '').toLowerCase();
const found = words.find((w) => value.includes(w));
return found ? { forbidden: { word: found } } : null;
};
}
// usage: username: ['', [Validators.required, forbiddenWords(['admin', 'root'])]]Because validators are pure functions of a value, you can write and test them in plain TypeScript. Here are three, run against sample inputs:
type Errors = Record<string, unknown> | null;
type ValidatorFn = (control: { value: unknown }) => Errors;
const required: ValidatorFn = ({ value }) =>
value === '' || value == null ? { required: true } : null;
const minLength = (n: number): ValidatorFn => ({ value }) => {
const len = String(value ?? '').length;
return len > 0 && len < n ? { minlength: { requiredLength: n, actualLength: len } } : null;
};
const forbiddenWords = (words: string[]): ValidatorFn => ({ value }) => {
const found = words.find((w) => String(value ?? '').toLowerCase().includes(w));
return found ? { forbidden: { word: found } } : null;
};
function validate(value: unknown, validators: ValidatorFn[]): Errors {
const merged = Object.assign({}, ...validators.map((v) => v({ value })));
return Object.keys(merged).length ? merged : null;
}
const rules = [required, minLength(4), forbiddenWords(['admin', 'root'])];
for (const input of ['', 'li', 'SuperAdmin', 'linh_dev']) {
console.log(JSON.stringify(input), '->', JSON.stringify(validate(input, rules)));
}"" -> {"required":true}
"li" -> {"minlength":{"requiredLength":4,"actualLength":2}}
"SuperAdmin" -> {"forbidden":{"word":"admin"}}
"linh_dev" -> null
Note: Angular's
minLength(like this one) ignores empty values — "required" is a separate concern, so you combine both.
Cross-field validation
Some rules involve two fields, like "passwords must match". Put the validator on the group:
interface Group { controls: Record<string, { value: string }>; }
function matchFields(a: string, b: string) {
return (group: Group) =>
group.controls[a].value === group.controls[b].value ? null : { mismatch: { fields: [a, b] } };
}
const passwordsMatch = matchFields('password', 'repeat');
console.log(passwordsMatch({ controls: { password: { value: 'secret42' }, repeat: { value: 'secret42' } } }));
console.log(passwordsMatch({ controls: { password: { value: 'secret42' }, repeat: { value: 'secret24' } } }));null
{ mismatch: { fields: [ 'password', 'repeat' ] } }
In Angular you attach it with fb.group({ password: [''], repeat: [''] }, { validators: passwordsMatch }) and read form.hasError('mismatch') in the template.
Async validators
Checking whether a username is already taken requires a server call. Async validators return a Promise or Observable of the errors object, and run only after all sync validators pass. While running, the control's status is 'PENDING':
import { Component } from '@angular/core';
import { AbstractControl, FormControl, ReactiveFormsModule, ValidationErrors } from '@angular/forms';
const TAKEN = ['mai', 'tuan', 'admin'];
async function usernameAvailable(control: AbstractControl): Promise<ValidationErrors | null> {
await new Promise((r) => setTimeout(r, 300)); // pretend to call the server
return TAKEN.includes(control.value) ? { taken: true } : null;
}
@Component({
selector: 'app-username',
imports: [ReactiveFormsModule],
template: `
<input [formControl]="name" />
@switch (name.status) {
@case ('PENDING') { <span>⏳ checking…</span> }
@case ('INVALID') { <span class="err">✖ taken</span> }
@case ('VALID') { <span class="ok">✔ available</span> }
}
`,
styles: `.err { color: #dd0031; } .ok { color: #2e7d32; }`,
})
export class Username {
name = new FormControl('tuan', { nonNullable: true, asyncValidators: [usernameAvailable], updateOn: 'blur' });
}updateOn: 'blur' validates when the user leaves the field instead of on every keystroke — a good choice for expensive checks.
Test yourself
What should a validator function return when the value is valid?
- true
- An empty string
- null
- { valid: true }
Where do you attach a "passwords must match" validator?
- On the password control
- On the confirm control
- On the FormGroup containing both
- In the template only
What is a control's status while an async validator is running?
- VALID
- INVALID
- PENDING
- DISABLED