Angular响应式表单——自定义验证器调用服务



Angular应用和响应式表单。我需要验证所创建的每个新记录的名称的唯一性。我让后端端点执行此操作并返回布尔值作为结果。现在我需要将它连接到表单字段,但我找不到这样做的方法。理想情况下,我需要一个自定义验证器,我可以添加到字段验证器中,但实际上任何解决方案都适合。

格式如下:

groupForm : FormGroup = new FormGroup({
shortName: new FormControl(null, [Validators.required,
Validators.minLength(1), Validators.maxLength(10), Validators.pattern(this.shortNameRegex)]),
fullName: new FormControl(null, [Validators.required,
Validators.minLength(1), Validators.maxLength(100)]),
emailDomains: new FormControl(null, [Validators.required]),
addressLine1: new FormControl(null, []),
addressLine2: new FormControl(null, []),
townCity: new FormControl(null, []),
county: new FormControl(null, []),
eircode: new FormControl(null, [Validators.pattern(this.eircodeRegex)]),
ratingScales: new FormControl(null, []),
});

下面是函数调用:

checkGroupUnique() {
this.onLenderGroupService.checkGroupUnique(this.groupForm.controls.shortName.value).subscribe(res => {
this.isGroupUnique = res;
});
}

但是我还没有在任何地方调用它,我需要将这样的验证器添加到名为&;shortname &;的第一个字段

可以在Angular中创建异步验证器:

groupForm = new FormGroup({
shortName: new FormControl(null, [Validators.required, ..., this.checkGroupUnique.bind(this)]),
...
checkGroupUnique(control: AbstractControl): Observable<ValidationErrors | null> {
return this.onLenderGroupService.checkGroupUnique(control.value).pipe(
map(isUnique => {
if (isUnique) {
return null; // no error
} else {
return { isGroupUnique: true };
}
})
);
}
<label *ngIf="groupForm.controls.shortName.errors?.isGroupUnique">
Group name is not unique!
</label>

最新更新