0 day streak
javascript / expert
Snippet

Declarative Form Validation with Custom ValidatorFn and Dynamic Error Structuring

Factory function creating a custom, parameterized Angular ValidatorFn for Reactive Forms. It evaluates password rules and returns detailed contextual error objects for granular UI error handling.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function createComplexityValidator(minLength: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = String(control.value || '');
if (!value) return null;
const hasUpper = /[A-Z]/.test(value);
const hasDigit = /\d/.test(value);
const isValid = value.length >= minLength && hasUpper && hasDigit;
return isValid ? null : { passwordComplexity: { requiredLength: minLength, hasUpper, hasDigit } };
};
}
angular
Breakdown
1
export function createComplexityValidator(minLength: number): ValidatorFn
Factory function returning a configured ValidatorFn closure bound with dynamic parameters.
2
return (control: AbstractControl): ValidationErrors | null => {
Defines the signature required by Angular Reactive Forms for synchronous control validation.
3
if (!value) return null;
Follows standard validator convention of ignoring empty values to allow composition with Validators.required.
4
return isValid ? null : { passwordComplexity: { requiredLength: minLength, hasUpper, hasDigit } };
Returns null on success or a structured object key containing validation details on failure.