Sub topic 10
Validator directives for template-driven forms
This chapter assumes you can write a synchronous validator function and a validator factory, and that you know the basics of FormControl, FormGroup, and ngModel. It shows how to make a custom validator work in a template-driven form by wrapping it in a directive.
Why template-driven forms need a directive
In a reactive form you build the control in TypeScript and pass validators to it directly. In a template-driven form, ngModel creates the FormControl for you behind the scenes. You never write new FormControl(...), so you have no place to pass a ValidatorFn.
Angular solves this with dependency injection. When NgModel creates its control, it asks the injector for every provider registered under the NG_VALIDATORS token, and it attaches them all to the control. A directive that sits on the same element as ngModel can register itself under that token. That is how built-in attributes such as required and minlength work. They are directives that provide NG_VALIDATORS.
The same mechanism exists for async validators, through the NG_ASYNC_VALIDATORS token. The pattern is identical, so this chapter focuses on the synchronous case and returns to async at the end.
The Validator interface
A validator directive implements the Validator interface from @angular/forms. The interface has one required method and one optional method.
| Member | Required | Purpose |
|---|---|---|
| `validate(control)` | Yes | Returns `ValidationErrors` or `null`, like any `ValidatorFn`. |
| `registerOnValidatorChange(fn)` | No | Gives the directive a callback to call when its configuration changes, so the control re-runs validation. |
The first method is the same contract you already know. The directive's job is to forward the call to your existing validator function. That keeps one implementation of the rule for both reactive and template-driven forms.
Wrapping a validator factory
Here is the directive from the plan. It reuses forbiddenNameValidator from the factory chapter.
import { Directive, Input } 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 {
@Input('appForbiddenName') forbiddenNames: string[] = [];
validate(control: AbstractControl): ValidationErrors | null {
return forbiddenNameValidator(this.forbiddenNames)(control);
}
}Three parts of this code matter.
provide: NG_VALIDATORSputs the directive into the list of validators thatNgModelreads.useExisting: ForbiddenNameDirectivetells the injector to hand out the directive instance Angular already created for this element. Without it, you would useuseClass, and Angular would create a second, separate instance that never receives the@Inputvalues.multi: truemakes the token hold an array. Several directives on one element, such asrequiredplus your own, each add to the array instead of replacing each other. If you leavemulti: trueout, your provider replaces the others and built-in validators silently stop working.
The @Input alias 'appForbiddenName' means the attribute carries both the selector and the configuration, so one attribute does both jobs.
Using the directive in a template
Import the directive in the component that uses it, along with FormsModule for ngModel.
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: `
<label for="name">Name</label>
<input
id="name"
name="name"
type="text"
required
[appForbiddenName]="['admin', 'root']"
[(ngModel)]="name"
#nameModel="ngModel"
/>
@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 NgModel directive, which gives you the same control API you use in reactive forms: invalid, dirty, touched, hasError, and getError. Error display works exactly as in the earlier chapter on showing errors.
Note the property binding [appForbiddenName]="['admin', 'root']". Because the input expects an array, you must bind with brackets. Writing appForbiddenName="admin" would pass the string "admin" and forbidden.includes(...) would then do a substring check on a string instead of an array lookup.
Reacting to input changes
There is a gap in the directive above. Suppose the parent changes forbiddenNames after the control has already been validated. The control does not know the rule changed, so its status stays stale until the user types again.
The registerOnValidatorChange method fixes this. Angular passes you a callback. When you call it, the control re-runs its validators.
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: ReactiveForbiddenNameDirective, multi: true },
],
})
export class ReactiveForbiddenNameDirective implements Validator, OnChanges {
@Input('appForbiddenName') forbiddenNames: string[] = [];
private onChange: () => void = () => {};
validate(control: AbstractControl): ValidationErrors | null {
return forbiddenNameValidator(this.forbiddenNames)(control);
}
registerOnValidatorChange(fn: () => void): void {
this.onChange = fn;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['forbiddenNames']) {
this.onChange();
}
}
}The check changes['forbiddenNames'] uses the property name, not the alias. SimpleChanges is keyed by the class property. Using changes['appForbiddenName'] is a common mistake, and it fails silently because the key never exists.
A directive without configuration
Not every validator takes parameters. The noWhitespaceValidator is a plain ValidatorFn, so the directive can use the attribute as a simple flag.
import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, ValidationErrors, Validator } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
@Directive({
selector: '[appNoWhitespace]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: NoWhitespaceDirective, multi: true },
],
})
export class NoWhitespaceDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
return noWhitespaceValidator(control);
}
}In the template, you write <input name="name" ngModel appNoWhitespace />. There is no input to declare, so the directive has no state and no need for registerOnValidatorChange.
Selectors: which elements get the validator
The selector decides where Angular applies your validator. A selector such as [appForbiddenName] matches any element with that attribute, including a <div> that has no form control. If ngModel is not on the same element, nothing reads the NG_VALIDATORS token and the directive does nothing, without any error message.
You can tighten the selector so mistakes show up earlier.
| Selector | Matches | Effect |
|---|---|---|
| `[appForbiddenName]` | Any element with the attribute | Works wherever a form directive is present. |
| `[appForbiddenName][ngModel]` | Only elements that also have `ngModel` | Template-driven only. |
| `[appForbiddenName][formControlName]` | Only elements bound to a named reactive control | Reactive only. |
| `[appForbiddenName][ngModel],[appForbiddenName][formControl],[appForbiddenName][formControlName]` | Any of the three | Works in both styles. |
The NG_VALIDATORS provider also works with reactive forms when the directive sits on an element with formControl or formControlName. The control reads the token there too. So one directive can serve both worlds. In practice, reactive code passes the function in TypeScript, so the directive mostly serves template-driven forms.
Cross-field validation in template-driven forms
A group-level validator needs a directive on the element that owns the NgForm or ngModelGroup. The directive receives the group, not a single control, and looks up its children with get.
import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, ValidationErrors, Validator } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
@Directive({
selector: '[appPasswordsMatch]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: PasswordsMatchDirective, multi: true },
],
})
export class PasswordsMatchDirective implements Validator {
validate(group: AbstractControl): ValidationErrors | null {
return passwordsMatchValidator(group);
}
}Place it on the form or on an ngModelGroup.
<form #f="ngForm" appPasswordsMatch>
<input name="password" type="password" ngModel required />
<input name="confirm" type="password" ngModel required />
@if (f.hasError('passwordsMismatch') && f.controls['confirm']?.touched) {
<p>Passwords do not match.</p>
}
</form>Two details to remember. The error lives on the form (f.hasError(...)), not on the confirm input. And f.controls['confirm'] can be undefined during the first render, because ngModel registers its controls asynchronously. The optional chaining ?. prevents an error in that moment.
Async validators in template-driven forms
For asynchronous rules, register under NG_ASYNC_VALIDATORS and implement AsyncValidator. The validate method returns a Promise or an Observable.
import { Directive, Input, inject } from '@angular/core';
import {
AbstractControl,
AsyncValidator,
NG_ASYNC_VALIDATORS,
ValidationErrors,
} from '@angular/forms';
import { Observable } from 'rxjs';
import { UsernameService, uniqueUsernameValidator } from './unique-username.validator';
export abstract class UsernameLookup implements UsernameService {
abstract isTaken(username: string): Observable<boolean>;
}
@Directive({
selector: '[appUniqueUsername][ngModel]',
standalone: true,
providers: [
{ provide: NG_ASYNC_VALIDATORS, useExisting: UniqueUsernameDirective, multi: true },
],
})
export class UniqueUsernameDirective implements AsyncValidator {
private readonly lookup = inject(UsernameLookup);
validate(control: AbstractControl): Observable<ValidationErrors | null> {
return uniqueUsernameValidator(this.lookup)(control) as Observable<ValidationErrors | null>;
}
}Using inject() gives the directive access to a service, so the validation logic still lives in the validator function you already wrote. Provide UsernameLookup in your application with a concrete class. The as Observable<...> cast is needed because AsyncValidatorFn is typed to return either a Promise or an Observable.
Remember that Angular only runs async validators when every sync validator on the control passes. If required fails, the lookup never starts, and the status goes straight to INVALID.
Common errors
- Forgetting
multi: true. The directive replacesrequired,minlengthand other validators on the same element. - Using
useClassinstead ofuseExisting. Angular creates a second instance without your@Inputvalues, soforbiddenNamesstays empty and the validator never fails. - Forgetting to import the directive. In a standalone component, a directive missing from
importsis just an unknown attribute. Angular may log an unknown-property error for bound inputs, but plain attributes are ignored without any warning. - Missing
nameattribute. Inside a<form>,ngModelrequires anameattribute or[ngModelOptions]="{ standalone: true }". Otherwise Angular throws an error when it tries to register the control. - Reading errors from the wrong object. Cross-field errors are on the group, not on the child controls.
- Using the alias in
SimpleChanges. Use the class property name.
Summary of the pattern
The recipe is the same for every case.
- Write the validator as a plain function or factory. Test it on its own.
- Create a directive that implements
Validator(orAsyncValidator). - Provide the directive under
NG_VALIDATORS(orNG_ASYNC_VALIDATORS) withuseExistingandmulti: true. - Forward
validateto the function. - Call the
registerOnValidatorChangecallback when the configuration input changes.
Exercise
A teammate writes a validator directive with providers: [{ provide: NG_VALIDATORS, useClass: MinWordsDirective }] on an input that also has required. Two things go wrong: required stops working and the minWords input is always at its default value. Which two changes in the provider fix both, and why does each one fix its problem?
Show answer
Replace useClass with useExisting: MinWordsDirective, and add multi: true. useExisting makes the injector return the directive instance Angular already created for the element, which holds the bound @Input values, so the validator sees the configured value instead of the default of a second instance. multi: true makes NG_VALIDATORS collect an array of providers, so this directive adds to required instead of replacing it.
Exercise
You bind [appForbiddenName]="names" and later the component assigns a new array to names. The control's status does not update until the user types. What do you add to the directive to fix this, and which key do you check in SimpleChanges?
Show answer
Implement OnChanges and registerOnValidatorChange(fn). Store fn in a field, and in ngOnChanges call it when changes['forbiddenNames'] is present. The key is the class property name forbiddenNames, not the alias appForbiddenName. Calling the callback makes the control re-run its validators.