Sub topic 6
Validator factories with parameters
This chapter assumes you can write a basic synchronous validator and attach it to a FormControl. It also assumes you know that a validator returns a ValidationErrors object or null. You should be comfortable with TypeScript closures and generics.
Why a plain validator is not enough
A ValidatorFn has a fixed signature. Angular calls it with one argument, the control, and expects ValidationErrors | null back. There is no place to pass settings such as a list of banned words or a minimum length.
A validator factory solves this. It is an ordinary function that accepts your configuration and returns a ValidatorFn. The returned function keeps access to the configuration through a closure, which is a function's access to variables from the scope where it was created.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(forbidden: string[]): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string') {
return null;
}
return forbidden.includes(value.toLowerCase())
? { forbiddenName: { value } }
: null;
};
}The outer function runs once, when you build the form. The inner function runs every time Angular validates the control.
Using the factory
Call the factory where you would otherwise pass a validator function. Notice the parentheses: you pass the result of the call, not the factory itself.
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { forbiddenNameValidator } from './forbidden-name.validator';
export const form = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: [
Validators.required,
forbiddenNameValidator(['admin', 'root']),
],
}),
});Angular's own Validators.minLength(3) and Validators.pattern(/x/) work the same way. They are factories that return validator functions.
Carrying details in the error value
The error value can be any object, not just true. Built-in validators do this too. minLength reports requiredLength and actualLength. Putting the offending value in the error lets the template show a specific message.
@if (form.controls.name.getError('forbiddenName'); as err) {
<p>"{{ err.value }}" is not an allowed name.</p>
}getError('forbiddenName') returns the error value, or null when that error is absent. The @if ... as form needs Angular 17 or later, and it only renders the block when the value is truthy.
A second example: validating against a pattern
Factories can take richer arguments, such as a regular expression and the error key to use.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenPatternValidator(pattern: RegExp): ValidatorFn {
const safePattern = new RegExp(pattern.source, pattern.flags.replace('g', ''));
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string' || value.length === 0) {
return null;
}
return safePattern.test(value)
? { forbiddenPattern: { pattern: pattern.source, value } }
: null;
};
}The g flag is removed because a global regular expression remembers lastIndex between test() calls. With the flag, the same input could pass on one call and fail on the next. Copying the pattern once, outside the returned function, avoids that.
Gotchas
- Arguments are fixed at creation. The closure captures the array or number you passed. If you mutate that array later, the validator sees the change, but Angular does not re-run it. Call
control.updateValueAndValidity()after such a change. - Replacing a validator. To change settings at runtime, call a factory again and use
control.setValidators(newValidator), thenupdateValueAndValidity().setValidatorsreplaces all existing sync validators on the control, so include the ones you still want. - Create once. Build validators when you build the form. If you create a new validator on every call from a getter or a template expression, you lose reference equality and make the code harder to reason about.
- Skip empty values. Return
nullfor empty input and leave the empty case toValidators.required. That way each validator reports only one kind of problem. - Normalize before comparing. The example lowercases the input but not the list. Lowercase the list as well if callers may pass
'Admin'.
Summary
| Piece | Runs | Receives | Returns |
|---|---|---|---|
| Factory | Once, at form setup | Your configuration | A `ValidatorFn` |
| Returned validator | On every validation | The control | `ValidationErrors` or `null` |
Exercise
Write a factory minWordsValidator(min: number): ValidatorFn for string values. What should it return for an empty string, and what error object should it return when the value has fewer than min words?
Show answer
Return null for empty or non-string values so Validators.required handles them. Otherwise split value.trim() on /\s+/, count the words, and return { minWords: { required: min, actual: count } } when count < min, or null when the count is enough.