Sub topic 2
Showing Errors with Custom Validators in Angular
Assume you know TypeScript, Angular templates, and reactive forms. A control is invalid when at least one validator returns an error. It is valid when every validator returns null.
Showing errors in the template
A template should usually wait until the user has interacted with a control. dirty means its value changed. touched means the user focused and left it.
<label for="name">Name</label>
<input id="name" type="text" [formControl]="form.controls.name" />
@if (form.controls.name.invalid &&
(form.controls.name.dirty || form.controls.name.touched)) {
@if (form.controls.name.hasError('required')) {
<p>Name is required.</p>
}
@if (form.controls.name.hasError('whitespace')) {
<p>Name cannot contain only whitespace.</p>
}
}hasError checks an error key returned by a validator. Angular combines errors from all validators attached to the control.
Validator factories with parameters
A validator factory is a function that accepts configuration and returns a validator. This avoids creating a separate function for every forbidden-name list.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(names: string[]): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string') {
return null;
}
return names.includes(value.toLowerCase())
? { forbiddenName: { value } }
: null;
};
}Attach the configured validator like any other validator:
name: new FormControl('', {
nonNullable: true,
validators: [
Validators.required,
forbiddenNameValidator(['admin', 'root']),
],
})The error value can carry details for a more specific message. The template can read it with getError('forbiddenName').
Validating several fields together
A cross-field validator belongs on the FormGroup, because it needs sibling controls.
export const passwordsMatchValidator: ValidatorFn = (
group: AbstractControl,
): ValidationErrors | null => {
const password = group.get('password')?.value;
const confirm = group.get('confirm')?.value;
return password === confirm ? null : { passwordsMismatch: true };
};
const form = new FormGroup(
{
password: new FormControl(''),
confirm: new FormControl(''),
},
{ validators: passwordsMatchValidator },
);Read the group error with form.hasError('passwordsMismatch'). Do not attach this error to one field unless the rule truly belongs to that field.
Exercise
Why should a password-matching validator be attached to the FormGroup?
Show answer
It compares sibling controls, so the group provides the correct validation context and owns the resulting error.