ValidatorOptional

matchFields

Check that two or more controls in a group hold the same value.

Installation

Import the class, and @use the entry point in your global styles. Nothing warns you when the @use is missing.

import { Component } from '@angular/core';
import { WrInput } from 'ngwr/input';
import { WrValidators } from 'ngwr/validators';

@Component({ imports: [WrInput] })
export class MyComponent {}

Live demo

The form starts with two values that disagree, and form.errors reports it at once.

form.errors: { "matchFields": { "fields": [ "password", "confirm" ] } }form.valid: falseconfirm.errors: { "match": { "target": "password" } }

Usage

import { FormControl, FormGroup } from '@angular/forms';
import { WrValidators } from 'ngwr/validators';

const form = new FormGroup(
  {
    password: new FormControl(''),
    confirm:  new FormControl(''),
  },
  { validators: [WrValidators.matchFields('password', 'confirm')] },
);

Pair it with match

<wr-form-field> cannot show a group error, so add match on the confirm control for the field message.

const form = new FormGroup(
  {
    password: new FormControl(''),
    confirm:  new FormControl('', [WrValidators.match('password')]), // field message
  },
  { validators: [WrValidators.matchFields('password', 'confirm')] },
);

Paths and arity

Names are get() paths. With more than two, each is compared with the first.

WrValidators.matchFields('billing.zip', 'shipping.zip');
WrValidators.matchFields('a', 'b', 'c');

API

NameDescriptionTypeDefault
signatureCall it with two or more control names. Add it to the group that owns them.(first: string, second: string, ...rest: readonly string[]) => ValidatorFn—
lookupget() paths: billing.zip, items.0. Name a leaf control. A missing name or a group turns the check off and warns in dev.——
error keyOn mismatch: { matchFields: { fields: [...] } } on the group. fields lists the compared names, never values.{ matchFields: { fields } }—
empty valuesnull, undefined and "" are equal. All empty passes; filled against empty fails.——
comparisonStrict ===: two Date objects for the same instant differ. Compare a primitive.——
disabled controlsSkipped. Fewer than two enabled names passes.——

See also