Sub topic 7
Validating Input with Built-in Validators
This chapter assumes you can already create FormControl and FormGroup instances, bind them with formGroup and formControlName, and work with standalone components. It covers the validators that ship in @angular/forms: the shape of the errors they report, how they combine, and the edge cases that catch people out. How to show errors based on touched and dirty state is covered in the next chapter.
How a Validator Works
A validator is a function that takes a control and returns either null, meaning the value is valid, or a ValidationErrors object, meaning it is invalid. Angular runs every validator on a control each time the value changes. It merges all the returned error objects into control.errors. If every validator returns null, control.errors is null and the status is VALID.
Sync validators always run before async validators. Async validators run only after every sync validator has passed. A later chapter covers async validators.
The Built-in Set
| Validator | Error key | Error value | Skips empty values? |
|---|---|---|---|
| `Validators.required` | `required` | `true` | No, empty is what it checks for |
| `Validators.requiredTrue` | `required` | `true` | No, the value must be exactly `true` |
| `Validators.minLength(n)` | `minlength` | `{ requiredLength, actualLength }` | Yes |
| `Validators.maxLength(n)` | `maxlength` | `{ requiredLength, actualLength }` | Yes |
| `Validators.min(n)` | `min` | `{ min, actual }` | Yes |
| `Validators.max(n)` | `max` | `{ max, actual }` | Yes |
| `Validators.email` | `email` | `true` | Yes |
| `Validators.pattern(p)` | `pattern` | `{ requiredPattern, actualValue }` | Yes |
| `Validators.nullValidator` | none | always `null` | n/a |
The validator factories use camelCase names, such as minLength. The error keys they produce are all lowercase, such as minlength. Checking hasError('minLength') is a common bug, and it always returns false.
Applying Validators
You can pass a single validator or an array of them. Pass them either as the second constructor argument or as the validators option.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const account = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [
Validators.required,
Validators.minLength(3),
Validators.maxLength(20),
Validators.pattern('[a-z0-9_]+'),
],
}),
age: new FormControl<number | null>(null, [
Validators.required,
Validators.min(13),
Validators.max(120),
]),
email: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
}),
acceptTerms: new FormControl(false, {
nonNullable: true,
validators: Validators.requiredTrue,
}),
});
account.controls.username.setValue('Al');
console.log(account.controls.username.errors);
// { minlength: { requiredLength: 3, actualLength: 2 },
// pattern: { requiredPattern: '^[a-z0-9_]+$', actualValue: 'Al' } }
account.controls.age.setValue(9);
console.log(account.controls.age.getError('min'));
// { min: 13, actual: 9 }
console.log(account.valid); // false
console.log(account.errors); // null: the group itself has no validatorsNote two things about this example. First, every failing validator reports its error, so one control can carry several error keys at once. Second, a group's errors contains only the errors from validators attached to the group itself. An invalid child makes the group INVALID, but its errors are not copied up to the group.
Using Error Details in Templates
The error payloads let you write messages that adapt to the value. Use getError to read a payload:
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-username-field',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<input [formControl]="username" />
@if (username.getError('minlength'); as err) {
<p>Need {{ err.requiredLength - err.actualLength }} more characters.</p>
}
@if (username.hasError('pattern')) {
<p>Use lowercase letters, digits, and underscores only.</p>
}
`,
})
export class UsernameFieldComponent {
username = new FormControl('', {
nonNullable: true,
validators: [Validators.minLength(3), Validators.pattern('[a-z0-9_]+')],
});
}Gotchas
Length and range validators ignore empty values
minLength, min, email, and pattern all treat null, undefined, and '' as valid. This lets optional fields stay valid while they are empty. If the field is mandatory, add Validators.required as well. An empty [] array does fail required, so required also works for multi-selects.
`min` and `max` are numeric
The min and max validators parse the value as a number. A value that is not a number, such as 'abc', passes because the parsed result is NaN. They do not compare dates or strings. For those cases you need a custom validator.
`pattern` anchoring depends on the argument type
When you pass a string, Angular adds ^ and $, so the whole value must match. When you pass a RegExp, Angular uses it exactly as given. That means /[a-z]+/ accepts 'ABCx', because the pattern only has to match somewhere in the value. Anchor your regex literals yourself. Also avoid the g and y flags. They make RegExp.test keep state in lastIndex, which can produce results that alternate between valid and invalid.
`email` is permissive
Validators.email follows the WHATWG HTML pattern, with small adjustments. It accepts a@b, which has no top-level domain. Treat it as a typo check and confirm real addresses on the server.
`requiredTrue` is for checkboxes
required accepts false, because false is not empty. Use requiredTrue for "I agree" checkboxes. It reports its error under the required key.
HTML attributes also add validators
ReactiveFormsModule includes directives such as RequiredValidator, MinLengthValidator, and PatternValidator. They match attributes like required or minlength on an element that has formControlName. Writing <input formControlName="name" required> therefore adds a second, attribute-driven validator on top of your model. Angular adds novalidate to forms automatically, so the browser's own popups stay off, but the logic is now split between two places. Keep validation in the model. Use aria-required if you only need the accessibility hint.
Changing Validators at Runtime
You can change a control's validators after you create it:
| Method | Effect |
|---|---|
| `setValidators(v)` | Replaces all sync validators |
| `addValidators(v)` | Adds validators, skipping ones already present |
| `removeValidators(v)` | Removes validators by function reference |
| `hasValidator(v)` | Checks for a validator by function reference |
| `clearValidators()` | Removes all sync validators |
None of these methods re-validate the control. After calling them, call updateValueAndValidity().
import { FormControl, Validators } from '@angular/forms';
const phone = new FormControl('', { nonNullable: true });
const phoneLength = Validators.minLength(7); // keep the reference
function setContactByPhone(enabled: boolean): void {
if (enabled) {
phone.addValidators([Validators.required, phoneLength]);
} else {
phone.removeValidators([Validators.required, phoneLength]);
}
phone.updateValueAndValidity();
}
setContactByPhone(true);
console.log(phone.hasError('required')); // true
setContactByPhone(false);
console.log(phone.valid); // trueValidators.compose([...]) merges several validators into one function and returns null if the array is empty. Since Angular accepts arrays directly, you seldom need compose. Validators.nullValidator is a no-op placeholder, useful when a validator is conditional and you need to pass something.
Exercise
A control has validators [Validators.minLength(5), Validators.pattern(/[0-9]/)]. What are its validity and errors for the values '', 'abc', and 'abcdefg'?
Show answer
'' is valid with errors null, because both validators skip empty values. 'abc' is invalid with { minlength: { requiredLength: 5, actualLength: 3 }, pattern: { requiredPattern: '/[0-9]/', actualValue: 'abc' } }. 'abcdefg' is invalid with only the pattern error, since it has no digit. A RegExp is not anchored, so any value that contains a digit would pass the pattern check.
Exercise
A teammate writes ctrl.removeValidators(Validators.max(100)) and then ctrl.updateValueAndValidity(), but the max error is still reported. Why, and how do you fix it?
Show answer
Validators.max(100) creates a new function, so it does not match the reference that was originally added, and nothing is removed. Store the validator once, for example const max100 = Validators.max(100). Use max100 for both addValidators and removeValidators, then call updateValueAndValidity().
Exercise
A terms checkbox uses Validators.required, yet the form is valid while the box is unchecked. Explain and fix it.
Show answer
An unchecked box has the value false, and required treats false as a non-empty value, so it passes. Use Validators.requiredTrue, which passes only when the value is exactly true. It reports its error under the required key.