Cross-field Validation in Reactive Forms

Showcase how to implement custom validators that consider multiple form fields, such as password and password confirmation match validation.
import { FormGroup, FormControl, Validators } from '@angular/forms';

// Custom validator function to compare two fields
function passwordMatchValidator(g: FormGroup) {
  return g.get('password').value === g.get('confirmPassword').value
     ? null : {'mismatch': true};

// Creating form group with custom validator
const form = new FormGroup({
  password: new FormControl('', [Validators.required]),
  confirmPassword: new FormControl('', [Validators.required])
}, { validators: passwordMatchValidator });

// Subscribe to form value changes to detect validity
form.valueChanges.subscribe(() => {
  if (form.hasError('mismatch')) {
    form.get('confirmPassword').setErrors([{ mismatch: true }]);
  } else {
This code creates a new FormGroup with two fields: 'password' and 'confirmPassword'. It adds a custom validator 'passwordMatchValidator' at the group level to check if both fields match. When the form value changes, it checks if there is a 'mismatch' error and updates the 'confirmPassword' field's errors accordingly.