MyInternships.in

Forms & Validation

Angular Custom Validators

A custom validator is a function that receives a control and returns null when valid or an error object when invalid. Async validators return an Observable or Promise, which is how uniqueness checks against a server are done.


What is Custom Validators in Angular?

A custom validator is a function that receives a control and returns null when valid or an error object when invalid. Async validators return an Observable or Promise, which is how uniqueness checks against a server are done.

Custom Validators example

Sync and async validators
TypeScript
// sync: no disposable email domains
export function noDisposableEmail(): ValidatorFn {
  const blocked = ['tempmail.com', 'mailinator.com'];
  return (control: AbstractControl): ValidationErrors | null => {
    const domain = String(control.value ?? '').split('@')[1];
    return domain && blocked.includes(domain) ? { disposableEmail: true } : null;
  };
}

// async: is this email already registered?
export function emailAvailable(api: ApiService): AsyncValidatorFn {
  return control =>
    api.checkEmail(control.value).pipe(
      map(taken => (taken ? { emailTaken: true } : null)),
      catchError(() => of(null))
    );
}

// usage
email: ['', [Validators.required, Validators.email, noDisposableEmail()], [emailAvailable(this.api)]]

How this works

Sync validators are the second argument, async validators the third. Async validators run only after every sync validator passes, which avoids pointless server calls.

Key points to remember

  • Return null for valid — anything else marks the control invalid.
  • The error object key becomes the key in control.errors.
  • Cross-field validation goes on the FormGroup, not on an individual control.
  • Debounce async validators so they do not fire on every keystroke.

Common mistakes with Custom Validators

  • Returning false instead of null for a valid control.
  • Putting an async validator in the sync array, where its Observable is treated as a truthy error.

Angular Custom Validators— Interview Questions & FAQs

How do I validate that two fields match, such as password and confirm password?+

Put the validator on the FormGroup rather than a control. It receives the group, reads both controls, and returns an error object on the group when they differ.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships