我最近遇到了这个问题,所以我创建了一个验证器来处理这个问题。作为注释,我依赖于lodash,但我只是使用它来删除非唯一和空值。
指令代码:
import { Directive, forwardRef, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormGroup, ValidationErrors } from '@angular/forms';
import * as _ from 'lodash';
@Directive({
selector: '[pugMatchValidator]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => MatchValidatorDirective), multi: true }
]
})
export class MatchValidatorDirective implements Validator {
// an array of the names of form controls to check
@Input('pugMatchValidator') controlsToMatch: string[];
constructor() { }
validate(formGroup: FormGroup): ValidationErrors | null {
let values = [];
if (this.controlsToMatch) {
for (let controlName of this.controlsToMatch) {
const control = formGroup.controls[controlName];
if (control && (control.touched || control.dirty)) {
values.push(control.value);
}
}
// compact removes empty and null values
// uniq gets rid of duplicate fields, so one value should remain if everything matches
values = _.uniq(_.compact(values));
if (values.length > 1) {
return { unMatchedFields: true };
}
}
return null;
}
}
接下来,只需传入要检查的控件数组:
<form name="SignUpForm" #SignUpForm="ngForm" [pugMatchValidator]="['Pwd', 'RptPwd']">
最后,您可以检查您的表单是否有效
SignUpForm.valid
编辑:
在您的情况下,要显示错误,您将使用如下方法:
<div *ngIf="SignUpForm.errors?.unMatchedFields && (RptPwd.touched || RptPwd.dirty)" class="ErrCls">
Passwords do not match
</div>