Sub topic 6
Add built-in validators
Validators are rules in the form's schema function. They keep the rule next to the field it checks, not in the template. This chapter covers the built-in validators in @angular/forms/signals, how to configure them, and how their results appear in field state.
This chapter assumes you can read TypeScript and Angular templates. It also assumes you know signal(), you have seen form() with a [field] binding, and you know that a field exposes state such as invalid() and errors() as signals. Signal Forms is experimental in Angular 21, so option names may change in later releases.
Where validators live
You declare validators inside the schema function, the second argument to form(). The function receives a path object that mirrors the shape of your model. Each validator takes a field path as its first argument and options last.
import { signal } from '@angular/core';
import { form, required } from '@angular/forms/signals';
const model = signal({ name: '' });
const nameForm = form(model, (path) => {
required(path.name, { message: 'Name is required' });
});The schema function runs once, when the form is created. It does not run on each keystroke. It only registers rules. Angular re-evaluates those rules reactively whenever the signals they read change.
The built-in validators
| Validator | Signature | Error `kind` | Fails when |
|---|---|---|---|
| `required` | `required(path, options?)` | `required` | The value is empty |
| `email` | `email(path, options?)` | `email` | The value is not a plausible email address |
| `min` | `min(path, 18, options?)` | `min` | A number is below the limit |
| `max` | `max(path, 120, options?)` | `max` | A number is above the limit |
| `minLength` | `minLength(path, 8, options?)` | `minLength` | A string or array is too short |
| `maxLength` | `maxLength(path, 40, options?)` | `maxLength` | A string or array is too long |
| `pattern` | `pattern(path, /regex/, options?)` | `pattern` | A string does not match the regular expression |
Each validator produces an error object with a kind string. You can use kind in the template to choose between messages, and it also works as the track key in @for.
A complete example
This sign-up form uses most of the validators. The model has a string, a number that can be empty, and a second string with a format rule.
import { Component, signal } from '@angular/core';
import {
form,
Field,
required,
email,
min,
max,
minLength,
maxLength,
pattern,
} from '@angular/forms/signals';
interface SignupModel {
username: string;
email: string;
age: number | null;
}
@Component({
selector: 'app-signup',
imports: [Field],
template: `
<form (submit)="onSubmit($event)">
<label>Username <input [field]="signupForm.username" /></label>
@if (signupForm.username().touched() && signupForm.username().invalid()) {
@for (error of signupForm.username().errors(); track error.kind) {
<p class="error">{{ error.message ?? error.kind }}</p>
}
}
<label>Email <input type="email" [field]="signupForm.email" /></label>
@if (signupForm.email().touched() && signupForm.email().invalid()) {
@for (error of signupForm.email().errors(); track error.kind) {
<p class="error">{{ error.message ?? error.kind }}</p>
}
}
<label>Age <input type="number" [field]="signupForm.age" /></label>
@if (signupForm.age().touched() && signupForm.age().invalid()) {
@for (error of signupForm.age().errors(); track error.kind) {
<p class="error">{{ error.message ?? error.kind }}</p>
}
}
<button type="submit" [disabled]="signupForm().invalid()">Sign up</button>
</form>
`,
})
export class SignupComponent {
private readonly model = signal<SignupModel>({
username: '',
email: '',
age: null,
});
protected readonly signupForm = form(this.model, (path) => {
required(path.username, { message: 'Choose a username' });
minLength(path.username, 3, { message: 'Use at least 3 characters' });
maxLength(path.username, 20, { message: 'Use at most 20 characters' });
pattern(path.username, /^[a-z0-9_]+$/, {
message: 'Use lowercase letters, digits, and underscores only',
});
required(path.email, { message: 'Email is required' });
email(path.email, { message: 'Enter a valid email address' });
required(path.age, { message: 'Age is required' });
min(path.age, 18, { message: 'You must be at least 18' });
max(path.age, 120, { message: 'Enter a realistic age' });
});
protected onSubmit(event: Event) {
event.preventDefault();
console.log(this.model());
}
}The template reads error.message ?? error.kind. A validator without a message option still produces an error, but the error has no message. Falling back to kind shows something useful in that case. In a real application you would map each kind to a translated string.
Validators run together
The validators for one field do not stop at the first failure. If a user types AB!, the username field fails minLength and pattern at the same time, and errors() contains both. The @for loop in the template shows both messages.
If you want to show only one message at a time, show the first error and ignore the rest:
protected firstMessage(errors: { kind: string; message?: string }[]) {
const [first] = errors;
return first ? (first.message ?? first.kind) : null;
}Order in the schema function is the order in errors(). Put required first so that it is the error users see first on an empty field.
Empty values and `required`
required is the validator that decides whether a field may be empty. The other validators follow the convention used by Reactive Forms: an empty value is not their concern. An empty email field fails required but not email, and an empty text field passes minLength(path.x, 3) until the user types something. If you want "optional, but valid when filled in," leave out required.
This is why the age field above uses a number | null model. An empty number input needs a value that means "nothing yet." required treats null as empty. A plain number with an initial 0 would count as filled in, and min(path.age, 18) would then fail immediately on a fresh form. Check how your Angular version maps an emptied number input before you rely on this. The API is experimental.
Dynamic limits and conditional rules
A validator's limit can often be read from state instead of fixed in the code. The when option from the course's earlier example restricts a validator to certain situations:
import { signal } from '@angular/core';
import { form, required, minLength } from '@angular/forms/signals';
const model = signal({ contactByPhone: false, phone: '' });
const contactForm = form(model, (path) => {
required(path.phone, {
when: ({ valueOf }) => valueOf(path.contactByPhone),
message: 'Phone is required when you ask to be called',
});
minLength(path.phone, 7, { message: 'Phone numbers have at least 7 digits' });
});The when callback receives a context with valueOf(), which reads another field's value. Because it reads signals, the rule turns on and off as contactByPhone changes. When when returns false, the validator adds no error.
Reading validation results
Validators write into the same state you read in the previous chapter. These are the signals you use most often:
field().errors()returns the list of error objects for that field.field().valid()andfield().invalid()report the field's own result.form().invalid()istrueif any field is invalid, which is why the submit button in the example can bind tosignupForm().invalid().
Nothing is stored. Each of these is derived from the model, so setting the model programmatically (for example, to load a saved draft) re-runs every validator without extra code.
Common mistakes
- Writing
minfor string length.minandmaxcompare numbers. UseminLengthandmaxLengthfor strings and arrays. - Forgetting
required. A field with onlyemailaccepts an empty value. Addrequiredif the value is mandatory. - Putting
/gon apatternregex. A global regular expression keeps state between calls, so a valid value can fail on the second check. Use a plain regex with anchors (^and$). - Showing errors too early. Without the
touched()check, a fresh form displays every error before the user has typed anything. - Relying on the browser. HTML attributes such as
requiredorminlengthon an<input>do not replace schema validators. Keep the rules in the schema so they apply to programmatic model changes too.
Exercises
Exercise
A user types "ab" into a username field with required, minLength(path.username, 3), and pattern(path.username, /^[a-z]+$/) in that order. Which kinds appear in errors()?
Show answer
Only minLength. The value is not empty, so required passes, and "ab" matches the lowercase pattern. Validators on one field all run, but only the ones whose rule fails add an error.
Exercise
Write schema rules for a quantity field (model type number | null) that must be present and between 1 and 10, and a note field that is optional but may not exceed 200 characters.
Show answer
form(model, (path) => { required(path.quantity); min(path.quantity, 1); max(path.quantity, 10); maxLength(path.note, 200); }). The note field has no required, so an empty note is valid, and maxLength only fails when the text is longer than 200 characters.