Sub topic 9
Pending state, updateOn and revalidation
This chapter assumes you can write sync and async validators, attach them to a FormControl or FormGroup, and read basic RxJS. It covers when validators run, what the PENDING status means, how updateOn changes timing, and how to force revalidation.
When validators run
By default, a control revalidates every time its value changes. Angular runs synchronous validators first. Asynchronous validators run only if every synchronous validator passes. This ordering means a cheap check like required can stop an expensive server call.
A control's status is one of four values:
| Status | Meaning |
|---|---|
| `VALID` | All validators passed. |
| `INVALID` | At least one validator returned errors. |
| `PENDING` | An async validator has started and has not emitted yet. |
| `DISABLED` | The control is excluded from validation. |
A group's status is derived from its children. If any child is PENDING and none is INVALID, the group is PENDING. An invalid child makes the group INVALID even while another child is still pending.
Reacting to the pending state
While a control is PENDING, valid and invalid are both false. Code that only checks invalid can therefore let a half-validated form through. Check pending explicitly, or use form.valid, which is false while pending.
<input id="username" type="text" [formControl]="form.controls.username" />
@if (form.controls.username.pending) {
<p>Checking availability...</p>
}
@if (form.controls.username.hasError('usernameTaken')) {
<p>That username is taken.</p>
}
<button type="submit" [disabled]="form.invalid || form.pending">Save</button>The button condition uses both flags. form.invalid alone would leave the button enabled during the check.
When a new value arrives while an async validator is running, Angular unsubscribes from the old validator's Observable and starts a new one. This is why the timer(300) pattern from the async validator chapter avoids sending a request for every keystroke. It also means an async validator must return an Observable that completes, or Angular never leaves PENDING. Operators like first() or take(1) are the usual fix for a source that never completes.
Controlling timing with updateOn
updateOn decides which DOM event pushes a new value into the control, and therefore when validation runs. It accepts three values:
'change': the default. Each input event updates the value.'blur': the value updates when the field loses focus.'submit': the value updates when the enclosing form is submitted.
Setting updateOn: 'blur' is the simplest way to reduce async traffic. The validator then runs once per visit to the field instead of once per keystroke.
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { uniqueUsernameValidator, UsernameService } from './unique-username.validator';
export function buildForm(service: UsernameService) {
return new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
asyncValidators: [uniqueUsernameValidator(service)],
updateOn: 'blur',
}),
email: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
}),
});
}Here username validates on blur and email validates on every change. A control's updateOn overrides the group's. If you set updateOn on the FormGroup options, every child inherits it unless the child sets its own.
Forcing revalidation
Validators run when the control's own value changes. They do not rerun when something they depend on changes. Two cases come up often:
- A validator factory closes over external state, such as a list of forbidden names that you update.
- A cross-field validator on a group depends on a sibling control, but the error you want to show is on a different control.
Call updateValueAndValidity() to rerun validators on demand. It recalculates the control's status and then propagates the result to its parent.
import { FormControl, FormGroup } from '@angular/forms';
const form = new FormGroup({
password: new FormControl('', { nonNullable: true }),
confirm: new FormControl('', { nonNullable: true }),
});
// Revalidate confirm whenever password changes.
form.controls.password.valueChanges.subscribe(() => {
form.controls.confirm.updateValueAndValidity();
});A group-level validator already reruns when any child changes, so a mismatch is caught from either field. The subscription above matters when confirm has its own validator that reads password.
updateValueAndValidity accepts options. { emitEvent: false } suppresses valueChanges and statusChanges, which prevents infinite loops when you call it from inside a valueChanges subscription on the same control. { onlySelf: true } skips the parent, so the group is not revalidated.
If you swap validators at runtime, for example to make a field required only when a checkbox is ticked, Angular does not revalidate automatically. Change them and call updateValueAndValidity():
import { FormControl, Validators } from '@angular/forms';
const phone = new FormControl('', { nonNullable: true });
export function setPhoneRequired(required: boolean): void {
if (required) {
phone.addValidators(Validators.required);
} else {
phone.removeValidators(Validators.required);
}
phone.updateValueAndValidity();
}removeValidators compares by function reference. Passing a new arrow function that looks identical removes nothing, so keep a reference to validators you plan to remove, or use the built-in ones as shown.
Common errors
- A form that never becomes valid because an async validator Observable does not complete.
- A submit button that is enabled during
PENDINGbecause onlyinvalidwas checked. - Adding or removing validators without calling
updateValueAndValidity(), which leaves stale errors. - Calling
updateValueAndValidity()from avalueChangessubscription on the same control withoutemitEvent: false, which loops.
Exercise
A username field has Validators.required and an async uniqueUsernameValidator. The user types quickly, and the form's Save button uses [disabled]="form.invalid". Why can the user click Save while the availability check is still running, and what should the binding be?
Show answer
While the async validator runs, the control and the form are PENDING, so invalid is false and the button is enabled. Use [disabled]="form.invalid || form.pending" (or !form.valid, since valid is false while pending).
Exercise
You set updateOn: 'blur' on a control and log control.value inside an (input) handler. The log shows the previous value. Why?
Show answer
With updateOn: 'blur', the control only receives the DOM value when the field loses focus, so control.value stays at the old value while the user types.