0 day streak
javascript / intermediate
Snippet

Cross-Field Validation and Custom Error Payload Generation

Custom validator functions in Angular reactive forms can evaluate multiple sibling controls within a FormGroup. If values differ, returning an error object populates the validation errors collection, enabling granular UI feedback.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function matchFieldsValidator(primaryKey: string, confirmKey: string): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
const primary = group.get(primaryKey)?.value;
const confirm = group.get(confirmKey)?.value;
if (primary && confirm && primary !== confirm) {
return { mismatch: { fields: [primaryKey, confirmKey], mismatchTime: Date.now() } };
}
return null;
};
}
angular
Breakdown
1
export function matchFieldsValidator(primaryKey: string, confirmKey: string): ValidatorFn {
Defines a higher-order factory function returning a configured ValidatorFn for two form field names.
2
return (group: AbstractControl): ValidationErrors | null => {
Receives the parent control group instance to inspect multiple child controls simultaneously.
3
return { mismatch: { fields: [primaryKey, confirmKey], mismatchTime: Date.now() } };
Constructs and returns a structured validation error payload when the field values do not match.