Sub topic 2
Anatomy of a validator function
This chapter assumes you know TypeScript functions and types, can build a basic reactive form with FormControl and FormGroup, and have seen an RxJS Observable. Here you will take a validator apart: its type, its inputs, its two possible return values, and the rules that keep it predictable. Later chapters cover attaching validators, showing errors, factories, groups, and async validators in detail.
What a validator is
A synchronous validator is a plain function. Angular calls it with a control, and it returns one of two things:
nullwhen the value is valid.- An object describing what is wrong when the value is invalid.
Angular declares the type in @angular/forms:
interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null;
}
type ValidationErrors = { [key: string]: any };You rarely write these types yourself. You annotate your function with ValidatorFn, or you write the parameter and return types explicitly. This is the whole contract. Angular does not care whether the function is a constant, a method, or the result of another function call. It only cares about the input and output shapes.
Here is a minimal validator that rejects values made only of whitespace:
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 parts of the contract
| Part | What it means | In the example |
|---|---|---|
| Input | The control being checked, typed as `AbstractControl`. It can be a `FormControl`, `FormGroup`, or `FormArray`. | `control` |
| Value access | Read the current value from `control.value`. | `control.value` |
| Valid result | Return `null`. | `return null` |
| Invalid result | Return an object. Each key names a problem. | `{ whitespace: true }` |
| Side effects | None. The function only reads the control and returns a result. | none |
The input is an AbstractControl
AbstractControl is the base class of FormControl, FormGroup, and FormArray. Angular passes the same kind of argument whether the validator is on a single input or on a whole group. This is why one function signature serves both field-level and cross-field validation.
AbstractControl is generic over its value type. When you annotate a parameter as plain AbstractControl, the type of control.value is any. TypeScript will not warn you if the value is a number, null, or an array. Your validator has to check at run time, which is why the example tests typeof value !== 'string' before calling .trim().
The output is null or an error object
The return type is a union, and the two branches mean different things to Angular:
nullmeans "no errors from this validator".- Any object means "this validator found at least one problem", even if the object is
{}. Angular treats a non-null result as an error, so an empty object would still make the control invalid. Returnnullexplicitly for valid values.
The keys of the object are the error names, such as whitespace. Templates and other code look them up by key with hasError('whitespace'). The chapter on returning errors covers how to design these keys and what to put in the values.
What Angular does with your function
Angular calls your validator whenever the control's value changes, and also when you call updateValueAndValidity() on it. For each run it gathers the results from all the validators on that control and merges them into one errors object. If that object has any keys, the control's status becomes INVALID. If it is empty, errors is null and the status becomes VALID.
Two details in this flow matter when you design validators:
- All synchronous validators on the control run, and their errors are merged. One failing validator does not stop the others from reporting. A control can have
requiredandwhitespaceerrors at the same time if both validators return errors. - Async validators only run when the synchronous ones all pass. This lets you keep cheap checks in sync validators and avoid wasting a network request on a value that is already invalid.
Disabled controls are exempt. A disabled control gets the status DISABLED and has no errors, so its validators do not decide the form's validity.
Handling empty values
The most common validator mistake is mishandling empty input. The convention in Angular is that a validator checks only the property it owns. Emptiness belongs to Validators.required.
Compare two versions of a validator that requires a value to start with a capital letter:
import { AbstractControl, ValidationErrors } from '@angular/forms';
// Problem: an empty field is reported as "not capitalized".
export function startsCapitalBad(control: AbstractControl): ValidationErrors | null {
const value: string = control.value;
return /^[A-Z]/.test(value) ? null : { startsCapital: true };
}
// Better: empty values are left for Validators.required to handle.
export function startsCapital(control: AbstractControl): ValidationErrors | null {
const value = control.value;
if (typeof value !== 'string' || value.length === 0) {
return null;
}
return /^[A-Z]/.test(value) ? null : { startsCapital: true };
}The bad version flags an empty, untouched field as invalid. That makes optional fields impossible: a user who leaves the field blank still gets an error. The built-in validators such as Validators.minLength and Validators.email follow the same rule. They return null for empty values, so you can combine them with Validators.required to make a field mandatory, or leave required out to make it optional.
The same early-return guard also protects you from unexpected types. A control created with new FormControl(null) has the value null, and a number input can produce a number. Without the guard, value.trim() throws a TypeError.
Rules that keep validators predictable
A validator runs often, sometimes on every keystroke. A few rules keep it safe.
Keep it pure
A pure validator returns the same result for the same control state and changes nothing. Do not modify the control, call setValue, or write to outside variables from inside a validator. Changing the control from inside a validator can trigger another validation run, which calls the validator again.
Purity also means the result depends only on the control. Suppose a validator reads a mutable variable declared outside it, such as a "maximum allowed" number in a component. When that number changes, Angular has no way to know the validator's result should change, so the control keeps its old status. You must call updateValueAndValidity() on the control yourself. If the limit is configuration, pass it through a validator factory so the dependency is explicit. Factories are the subject of a later chapter.
Keep it synchronous and fast
Because a sync validator runs inline with the value update, slow work blocks the user interface. Do not call the network, read from storage, or run heavy loops in one. If the check needs a server, write an async validator, which returns an Observable or Promise instead of an error object.
Beware of `this`
Angular calls your validator as a bare function, not as a method of your object. If you pass a class method as a validator, this is not what you expect:
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class SignupRules {
private readonly minAge = 18;
// Broken when passed by reference: `this` is undefined inside.
brokenAgeCheck(control: AbstractControl): ValidationErrors | null {
return control.value >= this.minAge ? null : { tooYoung: true };
}
// Works: an arrow function property captures `this`.
ageCheck = (control: AbstractControl): ValidationErrors | null => {
return control.value >= this.minAge ? null : { tooYoung: true };
};
}Passing rules.brokenAgeCheck in a validators array throws when Angular calls it, because this.minAge is read from undefined. Use an arrow function property, call .bind(this), or build the validator with a factory.
Running a validator by hand
Since a validator is just a function of a control, you can call it yourself. This is useful for learning and for debugging. You do not need a component, a template, or TestBed:
import { FormControl } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
console.log(noWhitespaceValidator(new FormControl(' '))); // { whitespace: true }
console.log(noWhitespaceValidator(new FormControl('Ada'))); // null
console.log(noWhitespaceValidator(new FormControl(''))); // null
console.log(noWhitespaceValidator(new FormControl(null))); // nullThe last two lines show the empty-value convention at work. The validator reports nothing for empty input, because that is a job for Validators.required.
Combining validators
You can put several validators on one control, and Angular merges their results as described earlier. You can also combine them into a single function with Validators.compose, which returns a new validator that runs each one and merges the errors:
import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
const nameRules: ValidatorFn | null = Validators.compose([
Validators.required,
Validators.maxLength(40),
noWhitespaceValidator,
]);
const errors: ValidationErrors | null = nameRules
? nameRules({ value: ' ' } as AbstractControl)
: null;
console.log(errors); // { whitespace: true }Validators.compose returns ValidatorFn | null. It returns null when you pass an empty list or only null entries, so the type forces you to handle that case. The cast to AbstractControl here is only to keep the demonstration short. In real code you pass a real control. Most of the time you will not call compose at all, because the validators array on a control does the same thing.
Merging has one consequence worth remembering. If two validators return the same key, the later one overwrites the earlier one in the merged object. Choose distinct keys for distinct problems.
Common mistakes
- Returning
{ valid: false }orfalsefor invalid input, andtruefor valid input. The contract isnullfor valid and an object for invalid. A returnedtrueorfalseis not aValidationErrorsobject and is misinterpreted. - Returning an error object for empty input in a validator that is not
required. - Reading
control.valueas a string without a type check. - Mutating the control or other state inside the validator.
- Passing an unbound class method.
- Doing slow or asynchronous work in a synchronous validator.
Exercise
A teammate writes const isEven: ValidatorFn = (c) => c.value % 2 === 0 ? null : { odd: true }; and uses it on an optional number field. Users complain that leaving the field empty shows an "odd" error. Why does it happen, and how do you fix it?
Show answer
An empty field has the value null or '', and null % 2 is 0 but '' % 2 is 0 too, while an untouched control created with undefined or a non-numeric string gives NaN, and NaN === 0 is false, so the validator returns { odd: true }. More generally, the validator does not follow the convention that empty values are left to Validators.required. Fix it by returning null early for empty or non-numeric input, for example: if (c.value === null || c.value === undefined || c.value === '') { return null; } before the modulo check. The field then stays valid when empty, and you add Validators.required only if the field is mandatory.
Exercise
Which two return values are valid from a synchronous validator, and what does Angular do when the merged result contains at least one key?
Show answer
A validator returns either null (valid) or a ValidationErrors object (invalid). When the merged errors object from all of a control's synchronous validators has at least one key, the control's errors property holds that object and its status becomes INVALID.