Sub topic 6
Validator factories with parameters
Prerequisites and scope
This chapter assumes you can write a basic ValidatorFn, attach it to a FormControl, and read control.errors in a template. You should also be comfortable with TypeScript closures and generics. If a validator returning ValidationErrors | null is still unfamiliar, review the earlier chapters on the validator function contract first.
By the end you will be able to build a validator factory, choose what its error value carries, avoid the common mistakes that make factories misbehave, and reuse the same factory in reactive and template-driven forms.
Why a plain validator is not enough
A ValidatorFn has a fixed signature. Angular calls it with one argument, the control, so the function has no place to receive settings such as a list of banned words or a minimum length.
You could hard-code the settings inside the validator. That works until you need the same rule with different values on another form. You would copy the function and change a constant, and the copies would drift apart.
A validator factory solves this. It is a function that takes configuration and returns a ValidatorFn. The returned function remembers the configuration through a closure, so Angular still sees the single-argument signature it expects.
Angular's own Validators.minLength(3) and Validators.pattern(/x/) work this way. Calling Validators.minLength(3) does not validate anything. It returns the validator, and Angular calls that later.
Anatomy of a factory
The following factory rejects values that appear in a list of forbidden names.
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;
};
}There are two layers:
- The outer function,
forbiddenNameValidator, runs once when you build the form. It receivesforbidden. - The inner arrow function runs every time Angular validates the control. It uses
forbiddenfrom the enclosing scope.
The distinction matters for performance and for correctness. Put work that depends only on configuration in the outer function, so it happens once. Put work that depends on the current value in the inner function.
Using the factory
You attach the result of calling the factory, 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']),
],
}),
});Note the difference between the two entries. Validators.required is already a ValidatorFn, so you pass it as is. forbiddenNameValidator(['admin', 'root']) is a call that produces one.
A common mistake: passing the factory uncalled
If you write validators: [forbiddenNameValidator], TypeScript reports an error because the factory's parameter type (string[]) does not match AbstractControl. This catches the mistake at compile time. With loosely typed code, such as an any cast, the bug is silent. Angular would call the factory with the control as forbidden, the function would return a validator that Angular never calls, and the control would always look valid.
What the error value carries
The error object maps an error key to a value. For simple rules, true is enough:
return { whitespace: true };For parameterized rules the value is a good place to put details that the template needs. Angular's minLength does this:
{ minlength: { requiredLength: 3, actualLength: 1 } }You can follow the same pattern in your own factories. The next example checks a minimum number of words and reports both the requirement and what the user typed.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function minWordsValidator(minWords: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string' || value.trim().length === 0) {
return null;
}
const actual = value.trim().split(/\s+/).length;
return actual >= minWords
? null
: { minWords: { required: minWords, actual } };
};
}The template can then show a message that reflects the configuration, so the text never disagrees with the rule:
@if (form.controls.bio.hasError('minWords')) {
<p>
Enter at least {{ form.controls.bio.getError('minWords').required }} words
(you have {{ form.controls.bio.getError('minWords').actual }}).
</p>
}getError(key) returns the value stored under that key, or null when the error is absent. hasError(key) returns a boolean.
Choosing error keys
Keep these rules in mind:
- Use a distinct key for each rule. Angular merges the errors of all failing validators into one object, so two validators that both return
{ invalid: true }overwrite each other. - Name the key after the rule, not the field.
forbiddenNameis reusable, whilenameInvalidis not. - Keep the shape of the value stable. Templates depend on it, so changing
{ required, actual }to{ min, got }breaks every message that reads it.
Empty values: who owns "required"?
Notice that both factories return null for an empty or non-string value. This is a convention Angular's built-in validators follow. A rule such as "must not be forbidden" says nothing about an empty field, and Validators.required is the validator responsible for rejecting it.
If every validator also complained about empty values, a blank field would show several errors at once, and optional fields could never be left empty. Keep each validator focused on a single rule and combine them in the array.
The same reasoning applies to type checks. A control's value can be null, a number, or an object depending on the input type. The typeof value !== 'string' guard makes the validator safe in those cases instead of throwing on value.toLowerCase().
Configuration that changes over time
A closure captures the values you pass, so a factory built once keeps using them. This is easy to forget when the configuration is not a constant.
const banned = ['admin'];
const validator = forbiddenNameValidator(banned);
banned.push('root'); // the validator sees this, because it holds the same arrayHere the array is shared by reference, so the push changes the rule, but Angular does not know that anything changed. The control keeps its current validity until something triggers validation. Two behaviors follow.
- If you mutate shared configuration, call
control.updateValueAndValidity()afterwards so existing values are checked again. - If you want the rule to be fixed once built, copy the input inside the factory:
const list = new Set(forbidden.map(s => s.toLowerCase())). This also makes lookups faster and moves the lowercase conversion into the outer function, where it runs once.
The copying version looks like this:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(forbidden: string[]): ValidatorFn {
const blocked = new Set(forbidden.map((name) => name.toLowerCase()));
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string') {
return null;
}
return blocked.has(value.toLowerCase())
? { forbiddenName: { value } }
: null;
};
}When the rule truly depends on state that changes, such as the current value of another control or a service setting, you have two options. You can read the current state inside the inner function, so it is fresh on each run. Or you can replace the validators with control.setValidators(...) and then call updateValueAndValidity(). The first option is simpler. The second is better when the rule changes rarely and you want to avoid reading state on every keystroke.
Typing factories
For factories with a single options object, define an interface. It documents the settings and keeps call sites readable:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export interface RangeOptions {
min: number;
max: number;
inclusive?: boolean;
}
export function numberRangeValidator(options: RangeOptions): ValidatorFn {
const { min, max, inclusive = true } = options;
if (min > max) {
throw new Error(`numberRangeValidator: min (${min}) is greater than max (${max})`);
}
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (value === null || value === '' || typeof value !== 'number') {
return null;
}
const ok = inclusive
? value >= min && value <= max
: value > min && value < max;
return ok ? null : { numberRange: { min, max, actual: value } };
};
}The throw sits in the outer function. A bad configuration is a programming error, so failing when the form is built is better than producing a validator that never passes. The error appears at startup, with a clear message, instead of surfacing as a puzzling invalid field in production.
Note that typeof value !== 'number' skips string values. An <input type="number"> bound through FormControl yields a number, but a plain text input yields a string. Decide which you expect and be explicit about it.
Reusing the factory in other places
Because the factory returns a plain function, you can use it in several contexts without change:
| Context | How it is attached |
|---|---|
| `FormControl` constructor | `validators: [forbiddenNameValidator(['admin'])]` |
| Existing control | `control.addValidators(forbiddenNameValidator(['admin']))` |
| Replace all validators | `control.setValidators([...])` |
| `FormBuilder` | `fb.control('', [forbiddenNameValidator(['admin'])])` |
| Template-driven form | Wrap in a directive implementing `Validator` |
Two details about the methods in the table:
- After
addValidators,setValidators, orremoveValidators, Angular does not re-run validation. CallupdateValueAndValidity()to apply the change. removeValidatorscompares function references. A factory call such asforbiddenNameValidator(['admin'])creates a new function each time, so removing it with a second call does nothing. Keep the instance in a variable if you plan to remove it later.
import { FormControl } from '@angular/forms';
import { forbiddenNameValidator } from './forbidden-name.validator';
const control = new FormControl('');
const noAdmin = forbiddenNameValidator(['admin']);
control.addValidators(noAdmin);
control.updateValueAndValidity();
// Later, using the same reference:
control.removeValidators(noAdmin);
control.updateValueAndValidity();Using a factory inside a directive
Template-driven forms cannot call a factory in the template. They need a directive registered under the NG_VALIDATORS token. The directive reads the parameter from an input and delegates to the factory.
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);
}
}The directive builds a new validator on every call to validate. For a small rule that cost is negligible and it always uses the latest input. Two things to remember:
multi: trueis required. Without it, your provider replaces the other validators registered under the token, includingrequired.- If the input changes after the first validation, Angular does not re-run validation by itself. Implement
registerOnValidatorChangeand call the callback fromngOnChangeswhen the input changes. The full treatment of template-driven validators comes in a later chapter.
Testing a factory
A factory is a pure function, so you can test it without TestBed. Test both the factory's configuration paths and the produced validator.
import { FormControl } from '@angular/forms';
import { forbiddenNameValidator } from './forbidden-name.validator';
describe('forbiddenNameValidator', () => {
const validator = forbiddenNameValidator(['admin']);
it('returns an error for a forbidden name', () => {
expect(validator(new FormControl('Admin'))).toEqual({
forbiddenName: { value: 'Admin' },
});
});
it('returns null for an allowed name', () => {
expect(validator(new FormControl('alice'))).toBeNull();
});
it('returns null for an empty value', () => {
expect(validator(new FormControl(''))).toBeNull();
});
it('uses the configuration it was built with', () => {
const other = forbiddenNameValidator(['root']);
expect(other(new FormControl('admin'))).toBeNull();
expect(other(new FormControl('root'))).not.toBeNull();
});
});The last test is specific to factories. It confirms that two validators built with different settings do not share state, which is the main promise of a factory.
Summary of rules
- A factory takes configuration and returns a
ValidatorFn. Attach the call result, not the factory. - Do setup work in the outer function and value-dependent work in the inner function.
- Return
nullfor empty and wrongly typed values, and leave emptiness toValidators.required. - Use a distinct error key per rule, and put the details a message needs into the error value.
- Validate configuration in the outer function and throw early on bad settings.
- Re-run validation with
updateValueAndValidity()after changing validators or shared configuration.
Exercise
A teammate writes validators: [minWordsValidator] in a FormControl where minWordsValidator(minWords: number): ValidatorFn is a factory. TypeScript accepts the line because the array is typed as any[]. What happens at runtime, and how do you fix it?
Show answer
Angular calls minWordsValidator with the control as its minWords argument. The call returns a validator function that nobody uses, so the control never reports an error and always looks valid. The fix is to call the factory, for example validators: [minWordsValidator(5)], and to avoid any[] so the compiler can catch the mistake.
Exercise
You build const v = forbiddenNameValidator(['admin']) and call control.addValidators(v). Later you call control.removeValidators(forbiddenNameValidator(['admin'])). The rule is still active. Why, and what should you change?
Show answer
removeValidators compares function references. The second call to the factory creates a different function object, so nothing matches and nothing is removed. Pass the same reference, control.removeValidators(v), and then call control.updateValueAndValidity() so the control is validated again without the rule.
Exercise
Write a factory maxItemsValidator(max: number): ValidatorFn for a control whose value is an array. It should return { maxItems: { max, actual } } when the array is too long and null otherwise, including when the value is not an array. Throw if max is negative.
Show answer
export function maxItemsValidator(max: number): ValidatorFn { if (max < 0) { throw new Error('maxItemsValidator: max must not be negative'); } return (control: AbstractControl): ValidationErrors | null => { const value = control.value; if (!Array.isArray(value)) { return null; } return value.length > max ? { maxItems: { max, actual: value.length } } : null; }; }