Sub topic 1
How Angular Forms Run Validation
Prerequisites
This chapter assumes TypeScript functions and types, Angular components and templates, and basic reactive forms with FormControl and FormGroup.
How Angular Forms Run Validation
Angular runs validators when a control's value or relevant state changes. A validator receives the control and returns either an error map or null. Angular combines the results and sets the control status:
VALIDmeans every validator passed.INVALIDmeans at least one validator returned an error.PENDINGis used while asynchronous validation runs.DISABLEDexcludes the control from validation and its parent value.
A FormGroup also runs validators. Its status reflects its child controls and its own validators.
Anatomy of a Validator Function
A synchronous validator follows the ValidatorFn contract. It accepts an AbstractControl and returns ValidationErrors | null.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const noWhitespaceValidator: ValidatorFn = (
control: AbstractControl,
): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string' || value.length === 0) {
return null;
}
return value.trim().length === 0 ? { whitespace: true } : null;
};The validator should not change the control. It should only inspect its value and report the result.
Returning Errors: `ValidationErrors` and `null`
ValidationErrors is an object whose keys identify failed rules. The value can be true or a details object. Angular merges errors from all failing validators.
Return null when the value passes. Returning {} is incorrect because any object means the control is invalid.
Attaching Validators to Controls and Groups
Pass custom validators beside built-in validators in a control's validators option.
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
export const form = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: [Validators.required, noWhitespaceValidator],
}),
});For rules involving siblings, attach the validator to the FormGroup. The group validator reports its error on the group, not automatically on an individual control.
Exercise
What must a validator return when its control value is valid?
Show answer
It must return null.