Sub topic 11
Writing a custom validator directive
This chapter assumes you can build a template-driven form with ngModel, you know the built-in validation attributes, and you can read control state through template reference variables. Built-in attributes such as required and minlength cover common cases. When a rule is specific to your application, you write a validator directive.
How a validator directive plugs in
In a template-driven form, Angular builds the FormControl for you. To add your own rule, you create a directive that does two things:
- It implements the
Validatorinterface, which has one method:validate(control). - It registers itself under the
NG_VALIDATORStoken withmulti: true, so Angular adds it to the control's validators and does not replace the built-in ones.
validate returns null when the value is valid. It returns an object when the value is invalid. The object's key becomes the error name in control.errors.
The directive
This directive rejects one specific value, such as admin, and ignores case.
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 matter here:
useExistingpoints the token at the directive instance Angular already created. UsinguseClasswould create a second instance that does not receive the@Inputvalue.- The selector is an attribute selector,
[forbiddenName]. The same name is the input, soforbiddenName="admin"both applies the directive and passes the forbidden value. - The error value is an object. You can put useful data in it, such as the rejected value, and read it in the template.
Using it in a component
Import the directive next to FormsModule and add the attribute to the 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">
<label for="username">Username</label>
<input
id="username"
name="username"
[(ngModel)]="username"
#u="ngModel"
required
forbiddenName="admin"
/>
@if (u.errors?.['forbiddenName'] && (u.dirty || u.touched)) {
<p role="alert">"{{ u.errors?.['forbiddenName'].value }}" is not allowed.</p>
}
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class UsernameComponent {
username = '';
}Typing Admin makes u.errors equal { forbiddenName: { value: 'Admin' } }, the control becomes invalid, and the Save button is disabled.
Common errors
- The directive is not imported. In a standalone component, the directive must appear in
imports. Otherwise the attribute is ignored and no error is reported. multi: trueis missing. Without it, your provider replaces the existing validators, and built-in rules such asrequiredstop working.- The input name does not match. The
@Inputalias must equal the selector attribute, or the value is never passed in. - Validation does not rerun when the input changes.
validateruns when the control's value changes. If the directive's own input changes later, the control is not revalidated automatically. To handle this, implementregisterOnValidatorChangeand call the stored callback fromngOnChanges.
Exercise
Why must the provider use multi: true when registering under NG_VALIDATORS?
Show answer
NG_VALIDATORS holds a list of validators for each control. With multi: true, your directive is added to that list. Without it, your provider replaces the list, and the built-in validators such as required and minlength stop running.
Exercise
What should validate return when the value is valid, and what does the key of the returned error object control?
Show answer
It returns null for a valid value. For an invalid value it returns an object, and each key becomes an error name in control.errors, so a template can check errors?.['forbiddenName'].