我正在尝试使用提供程序(后端NodeJS)创建自定义验证器(Ionic 3 + Angular 6)。 验证器的目的是检查伪造的唯一性。
验证器的代码为:
import { AbstractControl, ValidatorFn } from '@angular/forms';
import { RemoteDataServiceProvider } from './../../providers/remote-data-service/remote-data-service';
export class UserNameValidator {
public static alreadyExists(
remoteDataService: RemoteDataServiceProvider,
validatorField: { [key: string]: boolean }
): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== undefined || control.value !== null) {
remoteDataService.checkPseudo(control.value)
.subscribe((response: any) => {
if (response.status === 200) {
return null;
} else {
return validatorField
}
}, (error) => {
return validatorField;
});
}
return validatorField;
}
}
}
假设后端完成了这项工作,当提供的伪代码正确时,我得到200,但是我认为总是有一条消息提到某个用户拥有此伪代码。
HTML片段:
<ion-item>
<ion-label floating color="primary">{{ 'account.forms.pseudo' | translate }}</ion-label>
<ion-input type="text" formControlName="userName" class="form-control" required></ion-input>
</ion-item>
<div class="validation-errors">
<ng-container *ngFor="let validation of validationMessages.userName">
<div class="error-message" *ngIf="userName.hasError(validation.type) && (userName.dirty || userName.touched)">
{{ validation.message }}
</div>
</ng-container>
</div>
在TS中:
this.signupForm = this.formBuilder.group({
userName: [
this._account.userName,
[
Validators.required,
UserNameValidator.alreadyExists(this.remoteDataService, {alreadyExists: true}),
Validators.minLength(5),
Validators.maxLength(25),
Validators.pattern('^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$')
]
],
...
我认为我在该代码中缺少某些内容,但是看不到...
有什么想法吗?
致谢