[英]Angular Reactive Forms - custom validator calling service
Angular 应用程序和反应式 forms。我需要验证创建的每条新记录名称的唯一性。 我有后端端点执行此操作并返回 boolean 值作为结果。 现在我需要将它连接到表单字段,但我找不到这样做的方法。 理想情况下,我需要一个可以添加到字段验证器的自定义验证器,但实际上任何解决方案都适用。
这是表格:
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, []),
});
这是 function 电话:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.