AI Hints
Home›Angular Tutorial›Signal Forms, Custom Validators and Practice: A Signup Form
Angular · Lesson 89 of 120

Custom Validators

Your own rules.

⏱ 2 min read▶ Video at 1:46:45🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Built-in rules don't cover everything. Names without numbers, or two passwords that must match. We can write our own validators.

  • Built-in isn't enough
  • No numbers, matching passwords
  • Your own rules

A validator function

A validator is a function. It receives a control, and returns null when the value is fine. If not, it returns an error object, with a name for the error. A validator on a group can compare several fields.

keyvalue
(control) => ...receives the control
return nullvalid
return { noNumbers: true }an error, by name
On a groupcompare fields

validators.ts

No numbers tests the value for any digit. If it finds one, it returns the no numbers error. Passwords match runs on a group. It compares the password with the confirm field, and returns mismatch when they differ.

validators.tstypescript
import { ValidatorFn } from '@angular/forms';

export const noNumbers: ValidatorFn = control =>
  /\d/.test(control.value ?? '') ? { noNumbers: true } : null;

export const passwordsMatch: ValidatorFn = group =>
  group.get('password')?.value === group.get('confirm')?.value ? null : { mismatch: true };

No numbers

The name control uses our validator, just like a built-in one. The message checks for the no numbers error. We type R two D two. Run it. The digits broke our rule, and the message appears.

app.tstypescript
import { Component } from '@angular/core';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
import { noNumbers } from './validators';

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule],
  template: `
    <input [formControl]="name" placeholder="Name">
    @if (name.hasError('noNumbers')) { <p class="error">Names can't contain numbers.</p> }
  `,
})
export class App {
  name = new FormControl('', noNumbers);
}
Also uses validators.ts
import { ValidatorFn } from '@angular/forms';

export const noNumbers: ValidatorFn = control =>
  /\d/.test(control.value ?? '') ? { noNumbers: true } : null;

export const passwordsMatch: ValidatorFn = group =>
  group.get('password')?.value === group.get('confirm')?.value ? null : { mismatch: true };
Also uses actions.json
[{"type": "input", "text": "R2D2"}]

Summary

A custom validator returns null when valid, or an error object. Group validators compare fields. Next, some practice.

Key takeaways
  • ValidatorFn
  • return null
  • { mismatch: true }
Next up: Practice: A Signup Form — your turn