Sub topic 4
Attaching validators to controls and groups
This chapter shows where validators are registered in a reactive form and what Angular does with them afterward. It assumes you know TypeScript, Angular standalone components, FormControl and FormGroup, and basic RxJS. You should also have read the previous chapters on the validator function contract and the ValidationErrors object.
Where validators live
A validator is only a function until you attach it to an AbstractControl. FormControl, FormGroup, FormArray and FormRecord all extend AbstractControl, so each one can hold its own validators. Each control runs its own validators against its own value. A group validator receives the group, so it can read every child.
You can attach validators in four ways:
- In the constructor options of a control or group.
- Through
FormBuilder, which is shorthand for the same constructors. - After construction, with
setValidators,addValidatorsandremoveValidators. - Through directives, for template-driven forms (covered in a later chapter).
Attaching to a control
The recommended form is an options object with a validators array:
import { FormControl, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
export const name = new FormControl('', {
nonNullable: true,
validators: [Validators.required, noWhitespaceValidator],
});Pass the function itself. Do not call it. noWhitespaceValidator is a ValidatorFn, so you pass the reference. A validator factory such as forbiddenNameValidator(['admin']) must be called once, and you pass what it returns.
Angular combines the array into one validator with Validators.compose. Two rules matter here:
- Every validator in the array runs, in order. There is no short-circuiting after the first failure.
- The resulting
errorsobject merges the keys of all failing validators. If everything returnsnull,errorsisnull.
So an empty string that fails both required and a custom check produces an object with both keys, and the template can choose which to show.
There is an older positional form, new FormControl('', Validators.required, asyncValidator). It still works, but it is harder to read and cannot be combined with nonNullable. Prefer the options object.
Attaching to a group
A group validator goes in the second argument of the FormGroup constructor, again as validators:
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
export const signUp = new FormGroup(
{
password: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(8)],
}),
confirm: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
}),
},
{ validators: [passwordsMatchValidator] },
);The group validator receives the FormGroup as its AbstractControl argument. It reads siblings with group.get('password').
The two levels are separate:
| Property | Control (`password`) | Group (`signUp`) |
|---|---|---|
| `errors` | Errors from the control's own validators | Errors from the group's own validators only |
| `valid` / `invalid` | Reflects its own validators | `false` if the group validator fails or any enabled child is invalid |
| Error from `passwordsMatchValidator` | Never appears here | `signUp.errors` contains `passwordsMismatch` |
The key point is that signUp.errors does not contain the children's errors. A group can be invalid while its errors is null. That happens when a child failed and the group validator passed. To find out why a group is invalid, look at the child controls.
Using FormBuilder
FormBuilder produces the same objects with less typing. Use fb.nonNullable so that reset() returns controls to their initial values instead of null.
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
import { passwordsMatchValidator } from './passwords-match.validator';
@Component({
selector: 'app-sign-up',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<input type="text" formControlName="name" />
<input type="password" formControlName="password" />
<input type="password" formControlName="confirm" />
<button type="submit" [disabled]="form.invalid">Sign up</button>
</form>
`,
})
export class SignUpComponent {
private readonly fb = inject(FormBuilder);
readonly form = this.fb.nonNullable.group(
{
name: ['', [Validators.required, noWhitespaceValidator]],
password: ['', [Validators.required, Validators.minLength(8)]],
confirm: ['', Validators.required],
},
{ validators: passwordsMatchValidator },
);
submit(): void {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
console.log(this.form.getRawValue());
}
}In the array form ['', [validators]], the first item is the initial value and the second is a validator or an array of validators. A third item would be async validators.
The submit method calls markAllAsTouched() when the form is invalid. This makes every error visible, even for fields the user never visited. The next chapter uses that behavior in templates.
Changing validators at runtime
Sometimes a rule depends on other state. For example, a phone number is required only when the user ticks "contact me by phone". Angular provides these methods on every AbstractControl:
| Method | Effect |
|---|---|
| `setValidators(v)` | Replaces all sync validators. `null` removes them. |
| `addValidators(v)` | Appends one validator or an array. |
| `removeValidators(v)` | Removes validators by reference equality. |
| `clearValidators()` | Removes all sync validators. |
| `hasValidator(v)` | Returns `true` if that exact function is attached. |
Async validators have matching methods: setAsyncValidators, addAsyncValidators, removeAsyncValidators, clearAsyncValidators and hasAsyncValidator.
None of these methods re-run validation. After changing validators, you must call updateValueAndValidity(). Without it, valid, invalid and errors keep their old values until the next value change.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const phone = new FormControl('', { nonNullable: true });
const contactByPhone = new FormControl(false, { nonNullable: true });
export const contactForm = new FormGroup({ contactByPhone, phone });
contactByPhone.valueChanges.subscribe((wanted) => {
if (wanted) {
phone.addValidators(Validators.required);
} else {
phone.removeValidators(Validators.required);
}
phone.updateValueAndValidity();
});This works because Validators.required is a single shared function, so removeValidators finds the same reference. The next section shows a case where it does not.
The reference equality trap
removeValidators and hasValidator compare with ===. Validators created by a factory are new function objects on every call:
import { FormControl, Validators } from '@angular/forms';
const control = new FormControl('', [Validators.minLength(3)]);
// Does nothing: this is a different function object than the one attached.
control.removeValidators(Validators.minLength(3));
console.log(control.hasValidator(Validators.minLength(3))); // falseIf you plan to remove a factory-made validator later, store it in a variable when you create it and use that variable in both places. Otherwise, use setValidators to replace the whole list.
import { FormControl, Validators } from '@angular/forms';
const min3 = Validators.minLength(3);
const control = new FormControl('', [min3]);
control.removeValidators(min3);
console.log(control.hasValidator(min3)); // falseWhich updateValueAndValidity to call
Calling updateValueAndValidity() on a child also recalculates its ancestors, so the group's valid and errors are refreshed. The options are { onlySelf: true } and { emitEvent: false }:
onlySelf: truestops the update from propagating to the parent group. Use it only when you will update the parent yourself.emitEvent: falsesuppressesvalueChangesandstatusChanges. Use it when the call happens inside avalueChangessubscription on the same control, to avoid an infinite loop.
If you change a group's validators, call updateValueAndValidity() on the group.
Disabled controls and group validity
A disabled control is excluded from validation. Its status is DISABLED, its errors is null, and its validators do not run. The parent group ignores it when computing validity. Group .value also omits it, which is why getRawValue() appears in the sign-up example above.
This matters for group validators. If confirm is disabled, group.get('confirm')?.value still returns its value, because get returns the control. But the group's .value omits the key. A group validator that reads group.value and one that reads group.get(...) can behave differently. Reading through get is safer.
When you call enable(), Angular re-runs validation for that control and updates the parent.
The order of validation
For one control, Angular does this when the value changes:
- Run all sync validators and merge the results.
- If the sync result is
null, run async validators and set the status toPENDINGuntil they emit. - If the sync result has errors, skip async validators. They would waste a request on a value already known to be bad.
- Update the parent group, which runs its own validators.
Children are validated before their parent, so a group validator can rely on child errors already being up to date. It still should not assume the children are valid. A password check should return null for an empty pair, or leave empty fields to Validators.required, to avoid two overlapping messages.
Common errors
- Calling the validator instead of passing it.
validators: [noWhitespaceValidator()]calls the function with no control, and Angular then receives its return value (undefinedor an error object) instead of a function. The compiler usually catches it, butany-typed code may not. - Forgetting to call a factory.
validators: [forbiddenNameValidator]passes the factory, not aValidatorFn. The factory receives a control where it expects a string array and fails at runtime. - Placing a cross-field validator on a child control. It then only validates that control, and
control.get('other')returnsnullbecause aFormControlhas no children. Attach it to the common parent group. - Expecting
group.errorsto list child errors. It never does. Readgroup.controls.x.errorsorgroup.get('x')?.errors. - Not calling
updateValueAndValidity()after changing validators. The status stays stale until the next edit. - Using
setValidatorswhen you meantaddValidators.setValidatorsreplaces everything, includingValidators.requiredyou attached in the constructor. - Mutating the validator array after construction. Angular composes the array once, at construction. Pushing onto it later has no effect.
Putting it together
The following snippet attaches validators at every level and inspects the result, so you can see what each level reports. It runs as a plain script or in a test, with no component needed.
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
const form = new FormGroup(
{
password: new FormControl('abc', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(8)],
}),
confirm: new FormControl('xyz', { nonNullable: true }),
},
{ validators: passwordsMatchValidator },
);
console.log(form.controls.password.errors);
// { minlength: { requiredLength: 8, actualLength: 3 } }
console.log(form.errors);
// { passwordsMismatch: true }
console.log(form.status); // 'INVALID'After you set both fields to the same 8-character string, form.errors becomes null and form.status becomes 'VALID'.
Exercise
A form has a phone control with no validators. A subscriber to contactByPhone.valueChanges calls phone.addValidators(Validators.required) but not updateValueAndValidity(). The user ticks the box with phone empty. Is the form valid at that moment, and what happens when the user types a character and then deletes it? Explain, and give the one-line fix.
Show answer
The form is still valid at that moment. addValidators only changes the list of validators and does not re-run them, so the control keeps its earlier VALID status. After the user types a character and deletes it, the value change triggers validation with required now attached, so the control becomes invalid. The fix is to call phone.updateValueAndValidity() right after addValidators, so the status is correct as soon as the box is ticked.
Exercise
A FormGroup has two controls, a (invalid because of Validators.required) and b (valid), plus a group validator that always returns null. What are group.status, group.errors and group.controls.a.errors?
Show answer
group.status is 'INVALID', because one enabled child is invalid. group.errors is null, because it only holds the group validator's own result. group.controls.a.errors is { required: true }.
Exercise
Why does control.removeValidators(Validators.minLength(3)) fail to remove a minLength(3) validator that was attached earlier, and how do you make removal work?
Show answer
Validators.minLength(3) is a factory that returns a new function object on each call, and removeValidators compares by reference, so the new function does not match the attached one. Store the validator in a variable, for example const min3 = Validators.minLength(3), attach that variable, and pass the same variable to removeValidators. Alternatively, use setValidators to replace the entire list.