0
0
AngularHow-ToBeginner · 4 min read

How to Create Custom Validator in Angular: Simple Guide

In Angular, create a custom validator by writing a function that returns either null for valid input or an error object for invalid input. Use this function with Validators in your form controls to enforce custom validation rules.
📐

Syntax

A custom validator in Angular is a function that takes a FormControl as input and returns either null if the control value is valid, or an object with error details if invalid.

The function signature looks like this:

  • control: The form control to validate.
  • Returns null if valid, or an error object like { 'errorName': true } if invalid.
typescript
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export function customValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const value = control.value;
    // Your validation logic here
    const isValid = /* condition */;
    return isValid ? null : { 'customError': true };
  };
}
💻

Example

This example shows a custom validator that checks if the input contains the word 'angular'. It returns an error if the word is missing.

typescript
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

// Custom validator function
export function containsAngularValidator() {
  return (control: FormControl) => {
    const value = control.value || '';
    const hasAngular = value.toLowerCase().includes('angular');
    return hasAngular ? null : { 'missingAngular': true };
  };
}

@Component({
  selector: 'app-root',
  template: `
    <label for="input">Enter text containing 'angular':</label>
    <input id="input" [formControl]="inputControl" />
    <div *ngIf="inputControl.errors?.missingAngular && inputControl.touched" style="color:red">
      Text must include the word 'angular'.
    </div>
  `
})
export class AppComponent {
  inputControl = new FormControl('', [Validators.required, containsAngularValidator()]);
}
Output
When you type text without 'angular', a red error message appears: "Text must include the word 'angular'." When the text includes 'angular', no error shows.
⚠️

Common Pitfalls

  • Not returning null when the input is valid causes the form to always show errors.
  • Forgetting to handle empty or null values can cause runtime errors.
  • Not adding the validator function correctly to the form control will make it ineffective.

Always test your validator with different inputs to ensure it behaves as expected.

typescript
/* Wrong: returns error object even when valid */
function wrongValidator(control: FormControl) {
  return { 'error': true };
}

/* Right: returns null when valid */
function rightValidator(control: FormControl) {
  const valid = control.value === 'valid';
  return valid ? null : { 'error': true };
}
📊

Quick Reference

  • Custom validator returns null if valid, error object if invalid.
  • Use ValidatorFn type for type safety.
  • Attach validator to form controls in FormControl constructor or setValidators.
  • Test validators with various inputs to avoid bugs.

Key Takeaways

A custom validator is a function returning null for valid or an error object for invalid input.
Attach custom validators to form controls using the Validators array or setValidators method.
Always handle empty or null values inside your validator to avoid errors.
Test your validator thoroughly to ensure it behaves correctly in all cases.