Sub topic 11
Writing a custom validator directive
This chapter assumes you know how ngModel binds an input, how NgForm exposes #f="ngForm", and how the built-in attributes (required, minlength) set errors on a control. You should also be comfortable with Angular directives, dependency injection providers, and TypeScript interfaces.
Why validators are directives here
In reactive forms, a validator is a plain function that you pass to a FormControl. In template-driven forms you never construct the control yourself. NgModel creates it for you. The only way to attach custom logic is through the template, so the validator has to be something that you can write as an attribute. That something is a directive.
When NgModel builds its control, it collects every provider registered under the NG_VALIDATORS token on the same element. It combines them with the built-in validators such as required and runs them all. A custom validator directive therefore does two things:
- It implements the
Validatorinterface, which has one required method,validate. - It registers itself under
NG_VALIDATORSwithmulti: true, so that it adds to the list instead of replacing it.
The built-in required and minlength attributes use this same mechanism.
The validate contract
The validate method receives the AbstractControl and returns one of two things:
nullwhen the value is valid.- A
ValidationErrorsobject when it is invalid. This is a plain object whose keys are error names and whose values are any extra details you want to expose.
The key is what the template checks, as in name.errors?.['forbiddenName']. The value is free-form. It is often true, or an object that carries information for the message, such as the rejected value.
A complete example
The directive below rejects one specific name, which you pass in as the attribute value.
import { Directive, Input } from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from '@angular/forms';
@Directive({
selector: '[forbiddenName]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: ForbiddenNameDirective, multi: true },
],
})
export class ForbiddenNameDirective implements Validator {
@Input('forbiddenName') forbiddenName = '';
validate(control: AbstractControl): ValidationErrors | null {
const value = String(control.value ?? '').toLowerCase();
return this.forbiddenName && value === this.forbiddenName.toLowerCase()
? { forbiddenName: { value: control.value } }
: null;
}
}Three details deserve attention.
useExisting, notuseClass. The directive instance already exists because Angular created it for the element.useExistingpoints the token at that instance. WithuseClass, Angular would build a second, separate instance that never receives the@Inputvalue.multi: true. Without it, your provider would replace every other validator registered underNG_VALIDATORS. Built-in validators such asrequiredwould silently stop working on that element.- The forward reference.
ForbiddenNameDirectiveappears inside its own decorator, before the class is defined. This works because the provider is evaluated lazily when the directive is instantiated. If your build complains, wrap it inforwardRef(() => ForbiddenNameDirective).
Using the directive
Import the directive into the consuming standalone component and add the attribute to an ngModel input.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ForbiddenNameDirective } from './forbidden-name.directive';
@Component({
selector: 'app-username',
imports: [FormsModule, ForbiddenNameDirective],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="username">Username</label>
<input
id="username"
name="username"
[(ngModel)]="model.username"
#username="ngModel"
required
minlength="3"
forbiddenName="admin"
/>
@if (username.invalid && (username.dirty || username.touched)) {
<div role="alert">
@if (username.errors?.['required']) {
<p>Username is required.</p>
}
@if (username.errors?.['minlength']) {
<p>Username must be at least 3 characters.</p>
}
@if (username.errors?.['forbiddenName']) {
<p>"{{ username.errors?.['forbiddenName'].value }}" is not allowed.</p>
}
</div>
}
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class UsernameComponent {
model = { username: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Typing admin (or ADMIN, because the directive compares in lowercase) makes username.errors contain forbiddenName. The required and minlength checks still run, because the directive registered with multi: true.
Binding the validator to a component value
The attribute value does not have to be a string literal. A property binding works too:
<input name="username" [(ngModel)]="model.username" [forbiddenName]="blockedName" />This exposes a problem. When blockedName changes, the directive's input changes, but the control does not know that its validation rules changed. The control only re-runs validators when its own value changes. The user would see stale validity until they type again.
The Validator interface has an optional method for this case, registerOnValidatorChange. Angular passes you a callback. Call it whenever the validator's configuration changes, and the control re-validates.
import { Directive, effect, input } from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from '@angular/forms';
@Directive({
selector: '[forbiddenName]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: ForbiddenNameDirective, multi: true },
],
})
export class ForbiddenNameDirective implements Validator {
readonly forbiddenName = input('');
private onValidatorChange: () => void = () => {};
constructor() {
effect(() => {
this.forbiddenName();
this.onValidatorChange();
});
}
validate(control: AbstractControl): ValidationErrors | null {
const forbidden = this.forbiddenName().toLowerCase();
const value = String(control.value ?? '').toLowerCase();
return forbidden && value === forbidden
? { forbiddenName: { value: control.value } }
: null;
}
registerOnValidatorChange(fn: () => void): void {
this.onValidatorChange = fn;
}
}This version uses a signal input. The effect reads the signal, so it re-runs each time the bound value changes, and each run calls the registered callback. The first run happens before Angular registers the callback, which is harmless because the default is an empty function.
Common errors
| Symptom | Likely cause |
|---|---|
| Other validators such as `required` stop working | The provider is missing `multi: true`. |
| `validate` never runs | The directive is not in the component's `imports`, or the selector does not match the attribute. |
| The input value is always empty inside `validate` | You used `useClass`, so a second instance without inputs is being called. |
| Validity is stale after a bound value changes | `registerOnValidatorChange` is not implemented or never called. |
| `Cannot read properties of null` when reading the error | You read `errors.forbiddenName` without `?.`. The `errors` object is `null` when the control is valid. |
| Empty field shows a custom error | The validator does not handle empty values. |
The last row matters in practice. By convention, a validator should treat an empty value as valid and leave "must have a value" to required. That keeps the messages independent. If your validator rejects empty strings, the user sees two errors for one mistake. In the example above, an empty value never equals a non-empty forbidden name, so it passes.
Returning useful error details
The object you return is your own API to the template. Put in it what the message needs. For a numeric range validator, you might return { range: { min: 1, max: 10, actual: 15 } }. The template can then print "15 is above the maximum of 10" without recomputing anything.
Keep error keys distinct from the built-in names (required, minlength, maxlength, pattern, email, min, max). If two validators use the same key, the last one to run overwrites the other's details.
Testing the directive in isolation
Because validate is an ordinary method, you can unit test it without rendering anything. Build a FormControl and call the method directly.
import { FormControl } from '@angular/forms';
import { ForbiddenNameDirective } from './forbidden-name.directive';
import { TestBed } from '@angular/core/testing';
describe('ForbiddenNameDirective', () => {
it('flags the forbidden name regardless of case', () => {
const directive = TestBed.runInInjectionContext(
() => new ForbiddenNameDirective(),
);
expect(directive.validate(new FormControl('Admin'))).toBeNull();
});
});The test above passes only because the signal input defaults to an empty string, so nothing is forbidden. This shows why component-level tests matter: the input binding is part of the behavior. A fuller test renders a host component with forbiddenName="admin", types into the input, calls fixture.detectChanges(), and checks that the error message appears. A later chapter covers that approach.
Exercise
A teammate writes a validator directive with providers: [{ provide: NG_VALIDATORS, useExisting: MyDirective }], leaving out multi: true. The input also has required. What goes wrong, and how do you fix it?
Show answer
Without multi: true, the provider replaces the whole NG_VALIDATORS list on that element instead of adding to it, so the other validators registered under the token stop running and Angular may report an error about a non-multi provider. The fix is to add multi: true to the provider object.
Exercise
Your validator compares the control value to an input bound as [forbiddenName]="blockedName". After blockedName changes, the control still shows its old validity until the user types. Which method do you implement, and when do you call the callback it receives?
Show answer
Implement registerOnValidatorChange(fn) from the Validator interface and store fn. Call it every time the directive's input changes, for example from ngOnChanges or from an effect that reads a signal input. Angular then re-runs validation on the control.
Exercise
Write the validate body for a directive that rejects values containing spaces. It should return an error with key noSpaces and treat empty values as valid.
Show answer
validate(control: AbstractControl): ValidationErrors | null { const value = String(control.value ?? ''); return value && /\s/.test(value) ? { noSpaces: { value: control.value } } : null; }