Sub topic 6
Validating Input with Built-in Validators
This chapter assumes you can already create a FormControl and a FormGroup and bind them with formGroup and formControlName. It covers the validators that ship with Angular, the error objects they produce, and the edge cases that tend to surprise people.
How a Validator Works
A validator is a function. It takes a control and returns one of two things:
nullwhen the value is valid.- An error map such as
{ required: true }when the value is invalid.
Angular runs every validator on a control each time the control's value changes. It merges all the error maps into control.errors. If any errors exist, the control's status becomes INVALID, and a group containing that control becomes invalid too.
The Built-in Set
All built-in validators are static members of the Validators class.
| Validator | Error key | Error value |
|---|---|---|
| `Validators.required` | `required` | `true` |
| `Validators.requiredTrue` | `required` | `true` (for checkboxes that must be checked) |
| `Validators.email` | `email` | `true` |
| `Validators.min(n)` / `max(n)` | `min` / `max` | `{ min, actual }` / `{ max, actual }` |
| `Validators.minLength(n)` / `maxLength(n)` | `minlength` / `maxlength` | `{ requiredLength, actualLength }` |
| `Validators.pattern(p)` | `pattern` | `{ requiredPattern, actualValue }` |
Notice that the error keys for minLength and maxLength are all lowercase. Checking hasError('minLength') always returns false, and this is a common bug.
Applying Validators
You pass validators in the options object, or as the second constructor argument. To combine several validators on one control, pass them as an array.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const signup = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3), Validators.pattern('[a-z0-9_]+')],
}),
age: new FormControl<number | null>(null, [Validators.min(18), Validators.max(120)]),
terms: new FormControl(false, { nonNullable: true, validators: [Validators.requiredTrue] }),
});
signup.controls.username.setValue('Al');
console.log(signup.controls.username.errors);
// { minlength: { requiredLength: 3, actualLength: 2 },
// pattern: { requiredPattern: '^[a-z0-9_]+$', actualValue: 'Al' } }
signup.controls.age.setValue(16);
console.log(signup.controls.age.getError('min')); // { min: 18, actual: 16 }
console.log(signup.valid); // falseGotchas
- Empty values pass most validators.
minLength,min,max,email, andpatternall treat an empty value as valid. AddValidators.requiredif the field must be filled in. - Pattern anchoring depends on the argument type. When you pass a string, Angular wraps it in
^and$. When you pass aRegExp, Angular uses it exactly as written, so/[a-z]+/matches any value that contains a single letter. emailis permissive. It acceptsa@bbecause it has no top-level-domain check. Add apatternif you need a stricter rule.- Changing validators at runtime does not re-run them. After you call
addValidators,removeValidators, orsetValidators, callupdateValueAndValidity().
import { FormControl, Validators } from '@angular/forms';
const phone = new FormControl('', { nonNullable: true });
const phoneRequired = Validators.required;
phone.addValidators(phoneRequired);
phone.updateValueAndValidity();
console.log(phone.hasValidator(phoneRequired), phone.invalid); // true trueExercise
A control has validators [Validators.minLength(5)] and an empty string as its value. Is it valid, and what does hasError('minLength') return after you set the value to 'abc'?
Show answer
It is valid while empty, because minLength ignores empty values. After setting 'abc', the control is invalid, but hasError('minLength') returns false because the error key is 'minlength'. hasError('minlength') returns true.
Exercise
Why might Validators.pattern(/\d{4}/) accept the value 'abc12345'?
Show answer
A RegExp argument is not anchored automatically, so the regex only needs to find four digits somewhere in the value. Use the string '\\d{4}' or the regex /^\d{4}$/ to require exactly four digits.