我需要验证在我的应用程序的一个特定页面上重复多次的表单的唯一性,并且添加了一个自定义验证器,但它似乎没有触发。我想知道mat-error
是否是设置不正确,但是在出现必需的错误时它可以按预期工作。代码如下:
network.service.ts(先前的Names值已初始化,并在此文件中声明为空文件):
userNameValidator(userControl: AbstractControl) {
return new Promise((resolve) => {
setTimeout(() => {
if (this.validateUserName(userControl.value)) {
resolve({ userNameNotAvailable: true });
} else {
resolve(null);
}
}, 1000);
});
}
validateUserName(userName: string) {
return this.previousNames.indexOf(userName) > -1;
}
重复-name.directive.ts:
import { Directive, forwardRef } from '@angular/core';
import {
Validator,
AbstractControl,
NG_ASYNC_VALIDATORS,
} from '@angular/forms';
import { Observable } from 'rxjs';
import { NetworkService } from '../services/network.service';
@Directive({
selector: '[appValidateUserName]',
providers: [
{
provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => ValidateUserNameDirective),
multi: true,
},
],
})
export class ValidateUserNameDirective implements Validator {
constructor(private network: NetworkService) { }
validate(
control: AbstractControl
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> {
return this.network.userNameValidator(control);
}
}
网络-card.component.html:
<form #personForm="ngForm">
<div class="row">
<div class="col-lg-7">
<p>
<mat-form-field appearance="legacy">
<mat-label>Person Initials/Nickname</mat-label>
<input matInput type="text" name="name" minLength="2" id="name{{ count }}" [(ngModel)]="person.name"
appValidateUserName required />
<mat-error *ngIf="personForm.controls['name']?.errors?.appValidateUserName">
That name has already been used for another network member</mat-error>
<mat-error *ngIf="personForm.controls['name']?.errors?.required">
A name is required</mat-error>
<mat-hint>Enter a full name, nickname, initials or whatever is more
memorable.</mat-hint>
</mat-form-field>
</p>
这里没有显示的是this.network.previousNames值,每次将新卡添加到页面时都会更新。