Sub topic 9
Pending state, updateOn and revalidation
This chapter assumes you can write a synchronous validator, attach it to a FormControl, and write an async validator that returns an Observable. It covers when validators run, what status a control has while an async validator is in flight, and how to trigger validation by hand.
The four statuses
Every control, group, and array exposes a status string. It has one of four values:
| Status | Meaning |
|---|---|
| `VALID` | All sync and async validators passed. |
| `INVALID` | At least one validator returned an error. |
| `PENDING` | Sync validators passed and an async validator has not finished. |
| `DISABLED` | The control is disabled and is excluded from validation. |
The valid, invalid, pending, and disabled boolean properties are shortcuts for these values.
Angular runs validation in a fixed order:
- The sync validators run first.
- If any of them returns an error, the status becomes
INVALID. The async validators do not run at all, so no request is sent for a value that is already known to be bad. - If the sync validators pass, the async validators subscribe and the status becomes
PENDING. - When every async Observable has completed, Angular merges the results into the final
VALIDorINVALID.
A parent group derives its status from its children. If any child is INVALID, the group is INVALID. Otherwise, if any child is PENDING, the group is PENDING. This means form.valid is false while an async check is running, which is correct but can surprise you if you only watch form.invalid.
Cancellation and completion
Angular subscribes to your async validator's Observable on each validation run. When the value changes again before the previous run finishes, Angular unsubscribes from the earlier Observable. This is why the timer(300).pipe(switchMap(...)) pattern from the earlier chapter works. A cancelled run never reaches switchMap, so no request is sent.
Your Observable must also complete. Angular combines the async validators with forkJoin, which waits for completion. An Observable that emits once but never completes leaves the control PENDING forever. HTTP calls from HttpClient complete on their own. If you wrap a long-lived stream such as a WebSocket, add take(1).
Showing the pending state
Show a hint while the check runs and keep the submit button disabled until the status settles. This component uses a fake service so it can run as shown.
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { delay, of } from 'rxjs';
import { UsernameService, uniqueUsernameValidator } from './unique-username.validator';
const fakeService: UsernameService = {
isTaken: (name) => of(['alice', 'bob'].includes(name.toLowerCase())).pipe(delay(500)),
};
@Component({
selector: 'app-signup',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<label for="username">Username</label>
<input id="username" formControlName="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">Sign up</button>
</form>
`,
})
export class SignupComponent {
readonly form = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [uniqueUsernameValidator(fakeService)],
}),
});
submit(): void {
if (this.form.valid) {
console.log('Submitting', this.form.getRawValue());
}
}
}The form.pending check in [disabled] matters. Without it, a user could submit during the 500 ms window. At that moment form.invalid is false, so the button would be enabled even though the username has not been checked.
Controlling when validation runs with updateOn
By default, a control updates its value and runs validators on every input event. The updateOn option changes that trigger. It accepts three values:
| Value | The control updates its value and validates when |
|---|---|
| `'change'` | The user changes the value (default). |
| `'blur'` | The input loses focus. |
| `'submit'` | The enclosing form is submitted. |
This is useful for expensive checks. An async uniqueness check on blur sends one request per field visit instead of one per keystroke.
import { FormControl, Validators } from '@angular/forms';
import { uniqueUsernameValidator } from './unique-username.validator';
import { fakeService } from './fake-service';
export const username = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
asyncValidators: [uniqueUsernameValidator(fakeService)],
updateOn: 'blur',
});You can also set updateOn on a FormGroup or FormArray. Children inherit it unless they set their own value:
import { FormControl, FormGroup } from '@angular/forms';
export const form = new FormGroup(
{
email: new FormControl('', { nonNullable: true }),
nickname: new FormControl('', { nonNullable: true, updateOn: 'change' }),
},
{ updateOn: 'blur' },
);Here email validates on blur, and nickname overrides the group and validates on every change.
Keep these behaviors in mind:
updateOnonly affects changes from the user interface. CallingsetValue,patchValue, orresetin code updates the value and validates immediately, whateverupdateOnsays.- The control's value lags behind the input. With
'blur',control.valuekeeps the old value while the user types. With'submit', it stays stale until the form is submitted. Do not readcontrol.valuein aninputevent handler and expect to see the typed text. - Group validators see the lagging values. A cross-field validator such as
passwordsMatchValidatorreads child values. If a child waits for blur, the group is validated against the last committed value, not what is currently on screen. 'submit'needs a form directive. It works with[formGroup]on a<form>, or withngForm, because the directive emits the submit signal. A standaloneFormControlbound with[formControl]never receives it.
Revalidating by hand
A control revalidates only when its own value changes. A validator that reads another control's value therefore goes stale when that other control changes. Call updateValueAndValidity() to run all validators again and recompute the status.
This postal code validator depends on a sibling country control.
import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
import { Subscription } from 'rxjs';
export const postalCodeValidator: ValidatorFn = (
control: AbstractControl,
): ValidationErrors | null => {
const country = control.parent?.get('country')?.value;
const value = control.value as string;
if (!value) {
return null;
}
const patterns: Record<string, RegExp> = {
US: /^\d{5}$/,
NL: /^\d{4} ?[A-Z]{2}$/,
};
const pattern = patterns[country];
return !pattern || pattern.test(value) ? null : { postalCode: { country } };
};
export function createAddressForm() {
const form = new FormGroup({
country: new FormControl('US', { nonNullable: true }),
postalCode: new FormControl('', {
nonNullable: true,
validators: [postalCodeValidator],
}),
});
// Run once now: the first validation happened before the control had a parent.
form.controls.postalCode.updateValueAndValidity();
const link: Subscription = form.controls.country.valueChanges.subscribe(() => {
form.controls.postalCode.updateValueAndValidity();
});
return { form, link };
}Two details in this code are easy to miss:
- The parent is not set at first. Angular validates each control when it is constructed, before the group adopts it. At that point
control.parentisnull, and the optional chaining returnsundefined. This is whycreateAddressFormcallsupdateValueAndValidity()once after building the group. - The subscription needs cleanup. In a component, pipe the stream through
takeUntilDestroyed()or unsubscribe inngOnDestroy. Thelinkreturn value is there so the caller can unsubscribe.
Options of updateValueAndValidity
updateValueAndValidity accepts an options object with two flags.
| Option | Default | Effect when set |
|---|---|---|
| `onlySelf: true` | `false` | The parent is not revalidated. By default, validation propagates up the tree. |
| `emitEvent: false` | `true` | `valueChanges` and `statusChanges` do not emit. |
Use emitEvent: false when you call updateValueAndValidity inside a valueChanges subscription on the same control. Without it, the call emits again and the subscription loops forever.
Changing validators at runtime
setValidators, addValidators, removeValidators, clearValidators, and their Async variants change a control's validator list. They do not revalidate. The control keeps its old status until you call updateValueAndValidity():
import { FormControl, Validators } from '@angular/forms';
export function requireCompanyName(control: FormControl<string>, isBusiness: boolean): void {
if (isBusiness) {
control.addValidators(Validators.required);
} else {
control.removeValidators(Validators.required);
}
control.updateValueAndValidity();
}removeValidators compares function references. It only works if you pass the same function instance you added. Validators.required is a stable reference, but a validator created by a factory call such as forbiddenNameValidator(['admin']) produces a new function each time. Store that function in a variable if you plan to remove it later.
Waiting for async validation to finish
Sometimes code must act on a settled result, for example to submit only when the form is truly valid. Checking form.valid inside (ngSubmit) returns false if an async validator is still running. A small helper waits for the status to leave PENDING:
import { AbstractControl } from '@angular/forms';
import { Observable, filter, map, startWith, take } from 'rxjs';
export function whenSettled(control: AbstractControl): Observable<boolean> {
return control.statusChanges.pipe(
startWith(control.status),
filter((status) => status !== 'PENDING'),
take(1),
map((status) => status === 'VALID'),
);
}startWith(control.status) covers the case where the control is already settled, because statusChanges only emits on future changes. Use it in a submit handler with whenSettled(this.form).subscribe(valid => { if (valid) { ... } }).
Common errors
- A control stays PENDING forever. The async validator's Observable never completes. Add
take(1)orfirst(). - The error appears and never clears after another field changes. The validator reads a sibling, and nothing called
updateValueAndValiditywhen the sibling changed. - A stack overflow or an endless loop.
updateValueAndValidity()ran inside avalueChangessubscription of the same control withoutemitEvent: false. - A validator added with
addValidatorshas no effect. You did not callupdateValueAndValidity()afterward. - Errors do not show with
updateOn: 'blur'. The control only validates after the first blur. Showing errors based ondirty || touchedis compatible with this, but a "required" error will not appear while the user is still typing in the field.
Exercise
A signup form has username with Validators.minLength(3) and an async validator, and the user types "ab". Which status does the control have, and is the async validator called? What changes when the user types "abc"?
Show answer
With "ab" the sync minLength validator fails, so the status is INVALID and the async validator is not called. With "abc" the sync validators pass, so the status becomes PENDING and the async validator subscribes. When it completes, the status becomes VALID or INVALID depending on its result.
Exercise
A confirmEmail control has a validator that compares its value with a sibling email control. The user fixes a typo in email, but confirmEmail still shows a mismatch error. What is wrong, and how do you fix it?
Show answer
A control revalidates only when its own value changes, so confirmEmail never reran after email changed. Subscribe to email.valueChanges and call confirmEmail.updateValueAndValidity() in the callback. Alternatively, move the comparison into a group-level validator, which reruns whenever any child changes.