Sub topic 3
Writing Custom Validators
This chapter assumes you can build a typed FormGroup, bind it with formControlName, and read errors and touched from a control. It also assumes you know basic RxJS.
Custom and Cross-Field Validators
A ValidatorFn takes an AbstractControl and returns either null (valid) or an error object. If you attach it to a control, it checks that one value. If you attach it to a FormGroup, it can compare the group's children.
Async Validators and updateOn
An AsyncValidatorFn returns an observable of errors. Angular runs it only after every sync validator passes. While it runs, the control's status is PENDING. If you set updateOn: 'blur', the async check runs once, when the user leaves the field, and not on every keystroke. With 'submit', values and validation update only when the form is submitted.
import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
import { delay, map, of } from 'rxjs';
export function forbidden(word: string): ValidatorFn {
return (c: AbstractControl): ValidationErrors | null =>
c.value === word ? { forbidden: { word } } : null;
}
export const passwordsMatch: ValidatorFn = (g: AbstractControl): ValidationErrors | null =>
g.get('password')?.value === g.get('confirm')?.value ? null : { mismatch: true };
const takenNames = ['admin'];
export const signup = new FormGroup(
{
username: new FormControl('', {
nonNullable: true,
validators: [forbidden('root')],
asyncValidators: [
(c) => of(takenNames.includes(c.value)).pipe(
delay(300),
map((taken) => (taken ? { usernameTaken: true } : null)),
),
],
updateOn: 'blur',
}),
password: new FormControl('', { nonNullable: true }),
confirm: new FormControl('', { nonNullable: true }),
},
{ validators: passwordsMatch },
);Observing Changes
valueChanges emits every new value, and statusChanges emits VALID, INVALID, PENDING, or DISABLED. In a component, pipe either stream through debounceTime(300) and takeUntilDestroyed(this.destroyRef). That keeps the subscription from outliving the component.
Disabled Controls and Dynamic Forms
When you call control.disable(), two things happen. The control is skipped during validation, and its value is left out of form.value. Use form.getRawValue() when you need every value, disabled ones included.
You can change a form's shape at runtime. Use addControl and removeControl on a group, push and removeAt on a FormArray, or a FormRecord<FormControl<string>> when the keys are not known ahead of time.
Custom Form Controls
A component can work with formControlName if it implements ControlValueAccessor. That means implementing four methods: writeValue, registerOnChange, registerOnTouched, and setDisabledState. You also register the component under NG_VALUE_ACCESSOR in its providers. Call the stored onChange function whenever the user picks a value.
Testing
Validators are plain functions, so you can test them without rendering a template:
it('flags mismatched passwords', () => {
signup.patchValue({ password: 'a', confirm: 'b' });
expect(signup.hasError('mismatch')).toBe(true);
});Exercise
A username field has updateOn: 'blur' and an async validator. The user types "admin" but has not left the field yet. What do control.value and control.status report?
Show answer
value is still the previous value (initially ''), and status has not changed, because neither the value nor validation updates until blur. After blur, the status becomes PENDING while the async check runs, then INVALID with usernameTaken.