Sub topic 2
Anatomy of a validator function
This chapter assumes you know TypeScript functions and types, Angular components and templates, the basics of reactive forms (FormControl, FormGroup), and what an RxJS Observable is. Here you will take apart a synchronous validator and see what each piece does.
What Angular expects from a validator
A validator is a plain function. Angular calls it with a control, and the function returns one of two things:
nullwhen the value is valid.- A
ValidationErrorsobject when the value is invalid.
Angular defines this contract with the ValidatorFn type. It takes an AbstractControl and returns ValidationErrors | null. AbstractControl is the base class of FormControl, FormGroup and FormArray, so one signature covers all of them.
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;
};This validator rejects values that contain only spaces, tabs or line breaks. It has three parts.
- The input.
control.valueis the current value of the control. The validator reads it and never changes it. - The guard. If the value is not a string, or is empty, the function returns
null. Empty values are the job ofValidators.required. If every validator also complained about empty input, each empty field would show several errors at once. - The check and result.
value.trim().length === 0is true only when the string held nothing but whitespace. The function then returns{ whitespace: true }. Otherwise it returnsnull.
The error object
The returned object maps an error key to a value. The key (whitespace) is the name you will use later to look up the error. The value can be anything. true is common when there is nothing more to say. A richer value can carry details, such as the rejected input or a limit.
const result = noWhitespaceValidator(new FormControl(' '));
// { whitespace: true }Angular stores this object in the control's errors property and sets the control's status to INVALID. When the validator returns null, errors becomes null and the status becomes VALID, assuming no other validator failed.
Attaching the validator
You pass validators in the validators option when you create the control. Built-in and custom validators go in the same array.
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],
}),
});Angular runs every validator in the array and merges the error objects of those that fail. A control with the value ' ' passes required, because the string is not empty, but fails noWhitespaceValidator. Its errors property is { whitespace: true }. An empty control fails only required, because the custom validator returns null for empty input.
The next chapters cover attaching in more detail. For now, the point is that your function is used exactly like Validators.required.
Rules to keep in mind
- Return
null, notundefinedorfalse. Angular treats any non-null result as an error. A validator that returnsfalseto mean "valid" will mark the control invalid. - Do not mutate the control. A validator should be a pure function of the control's current state. Changing the value inside a validator can trigger another validation run.
- Handle unexpected types. Controls can hold
null, numbers or objects. Check the type before calling string methods, as the guard above does. - Keep it synchronous and fast. Angular runs validators on every value change. Work that needs a network call belongs in an async validator, which a later chapter covers.
Reading the result
Because a validator is a function, you can call it directly and look at the result. This is useful when you debug.
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(''))); // nullOn a live control you can also read control.errors and control.hasError('whitespace'). Showing these in a template is the subject of a later chapter.
Exercise
A validator contains the line return value.length >= 3 ? { tooShort: false } : { tooShort: true };. Why does the control stay invalid for long values, and how do you fix it?
Show answer
Both branches return a non-null object, and Angular treats any non-null result as an error. Even { tooShort: false } makes the control invalid. Fix it by returning null in the valid case: return value.length >= 3 ? null : { tooShort: true };.
Exercise
Why does noWhitespaceValidator return null for an empty string instead of an error?
Show answer
Rejecting empty values is the job of Validators.required. If the custom validator also reported an error for empty input, the field would show two errors for one problem, and you could not use the validator on optional fields.