Sub topic 10
Validator directives for template-driven forms
This chapter assumes you can write a validator function and a validator factory, as covered earlier in this tutorial. It also assumes you know basic ngModel usage and that you use standalone components. You will wrap forbiddenNameValidator in a directive so it works with ngModel.
Why a directive is needed
In a reactive form you pass validator functions to FormControl in TypeScript. In a template-driven form you never create the controls yourself. ngModel creates them from the template. The only place to attach a validator is an attribute on the element, and an attribute needs a directive behind it.
The directive does two jobs:
- It registers itself under the
NG_VALIDATORStoken, songModelfinds it. - It implements
Validator.validate()and delegates to the existing validator function.
The validation logic stays in one function that both form styles can share.
Correction: the diagram must be in a diagram mermaid fence, so here it is.
The directive
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, ValidationErrors, Validator } from '@angular/forms';
import { forbiddenNameValidator } from './forbidden-name.validator';
@Directive({
selector: '[appForbiddenName]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: ForbiddenNameDirective, multi: true },
],
})
export class ForbiddenNameDirective implements Validator, OnChanges {
@Input('appForbiddenName') forbiddenNames: string[] = [];
private onValidatorChange: () => void = () => {};
validate(control: AbstractControl): ValidationErrors | null {
return forbiddenNameValidator(this.forbiddenNames)(control);
}
registerOnValidatorChange(fn: () => void): void {
this.onValidatorChange = fn;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['forbiddenNames']) {
this.onValidatorChange();
}
}
}Each part has a purpose:
multi: trueadds the directive to the list of validators. Without it, you would replace the built-in ones such asrequired.useExistingpoints the token at the instance Angular already created for the element.useClasswould create a second instance with no input values.registerOnValidatorChangeis optional but important. The control does not know that your input changed. Calling the stored callback makes it revalidate.
Using it in a component
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ForbiddenNameDirective } from './forbidden-name.directive';
@Component({
selector: 'app-signup',
standalone: true,
imports: [FormsModule, ForbiddenNameDirective],
template: `
<input
name="name"
[(ngModel)]="name"
#nameModel="ngModel"
required
[appForbiddenName]="['admin', 'root']"
/>
@if (nameModel.invalid && (nameModel.dirty || nameModel.touched)) {
@if (nameModel.hasError('required')) {
<p>Name is required.</p>
}
@if (nameModel.hasError('forbiddenName')) {
<p>"{{ nameModel.getError('forbiddenName').value }}" is not allowed.</p>
}
}
`,
})
export class SignupComponent {
name = '';
}The template reference #nameModel="ngModel" exports the control state. From there, hasError, getError, dirty and touched work as they do in reactive forms. The error key is the same one the shared function returns, forbiddenName.
Two requirements are easy to miss:
- The directive must be in the component's
imports. If it is not, Angular treats[appForbiddenName]as an unknown property binding and reports an error. Nothing is validated. - The input needs a
nameattribute when it sits inside a<form>.ngModelregisters the control under that name.
Common errors
| Symptom | Likely cause |
|---|---|
| The validator never runs | The directive is missing from `imports`, or the selector does not match the attribute. |
| Other validators such as `required` stop working | `multi: true` is missing from the provider. |
| Changing the bound list does not update validity | `registerOnValidatorChange` is not implemented or never called. |
| Error appears before the user types | The template does not check `dirty` or `touched`. |
| Error appears on the form but not the control | The check reads the form's `errors`, not the control's. |
Testing the directive
You can still test the validator function alone, as the testing chapter shows. The directive adds only a thin layer. A small test can call new ForbiddenNameDirective(), set forbiddenNames, and call validate(new FormControl('admin')). A full component test is needed only to check the wiring, for example that the directive is imported and the selector matches.
Exercise
A template-driven input uses [appForbiddenName]="names", where names is an array on the component. The component replaces the array with a new one after a button click, but the control's validity stays the same until the user types. What is missing in the directive, and how do you fix it?
Show answer
The directive does not tell the control to revalidate when its input changes. Implement registerOnValidatorChange(fn) and store fn. Then implement ngOnChanges and call the stored function when changes['forbiddenNames'] is present. The control then reruns validate() with the new array.