How to create custom validators in Angular

Creating custom validators enables specialized validation logic that goes beyond Angular’s built-in validators for business-specific requirements. With over 25 years of experience in software development and as the creator of CoreUI, I’ve built countless custom validators for enterprise applications and complex business rules. From my expertise, the most reliable approach is creating validator functions that return validation error objects or null for valid inputs. This pattern provides flexible, reusable validation logic that integrates seamlessly with Angular’s reactive forms system.

Create validator functions that return error objects for invalid inputs or null for valid inputs.

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'

export function passwordStrengthValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const value = control.value
    if (!value) return null

    const hasNumber = /[0-9]/.test(value)
    const hasUpper = /[A-Z]/.test(value)
    const hasLower = /[a-z]/.test(value)
    const hasSpecial = /[#?!@$%^&*-]/.test(value)

    const valid = hasNumber && hasUpper && hasLower && hasSpecial && value.length >= 8
    return valid ? null : { passwordStrength: true }
  }
}

Here the validator function checks if a password meets specific strength criteria including numbers, uppercase letters, lowercase letters, special characters, and minimum length. The function returns null for valid passwords or an error object { passwordStrength: true } for invalid ones. Use it in reactive forms with password: ['', [Validators.required, passwordStrengthValidator()]]. The error key passwordStrength can be checked in templates to display specific error messages.

Best Practice Note:

This is the same approach we use in CoreUI Angular components for specialized validation like password strength, custom date ranges, and business rule validation. Always return null for valid inputs and descriptive error objects for invalid inputs to maintain consistency with Angular’s validation system.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author