typescript
53 lines · 7 steps
Cross-field password validation in Angular
A group-level validator confirms two password fields match without clobbering the field's other errors.
Explained by
highlit
1import { Component } from '@angular/core';
2import {
3 AbstractControl,
4 FormBuilder,
5 FormGroup,
6 ValidationErrors,
7 ValidatorFn,
8 Validators,
9} from '@angular/forms';
10
11function passwordsMatch(): ValidatorFn {
12 return (group: AbstractControl): ValidationErrors | null => {
13 const password = group.get('password')?.value;
14 const confirm = group.get('confirmPassword');
15
16 if (!confirm) {
17 return null;
18 }
19
20 if (password !== confirm.value) {
21 confirm.setErrors({ ...confirm.errors, passwordMismatch: true });
22 return { passwordMismatch: true };
23 }
24
25 if (confirm.hasError('passwordMismatch')) {
26 const { passwordMismatch, ...rest } = confirm.errors ?? {};
27 confirm.setErrors(Object.keys(rest).length ? rest : null);
28 }
29
30 return null;
31 };
32}
33
34@Component({
35 selector: 'app-register-form',
36 templateUrl: './register-form.component.html',
37})
38export class RegisterFormComponent {
39 readonly form: FormGroup = this.fb.group(
40 {
41 email: ['', [Validators.required, Validators.email]],
42 password: ['', [Validators.required, Validators.minLength(8)]],
43 confirmPassword: ['', Validators.required],
44 },
45 { validators: passwordsMatch() },
46 );
47
48 constructor(private readonly fb: FormBuilder) {}
49
50 get confirmPassword(): AbstractControl {
51 return this.form.controls['confirmPassword'];
52 }
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Cross-field rules belong on the FormGroup, not on a single control, so they can read sibling values.
- 2When setting errors on a control, merge rather than overwrite to preserve validators like required.
- 3A validator must actively clear its own error once the condition passes, or stale errors linger.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; import { DataSource } from 'typeorm';
Per-tenant database connections in NestJS
multi-tenancy
connection-pooling
dependency-injection
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/cross-field-password-validation-in-angular-explained-typescript-553a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.