【发布时间】:2017-09-08 01:20:29
【问题描述】:
我在我的项目中应用 Angular 4,但在使用 HTTP 请求进行自定义验证时遇到问题。
我也试过这个:How to implement Custom Async Validator in Angular2。
但它在我的项目中不起作用。
这是我到目前为止所做的:
验证投标:
userName: ['', [Validators.required, Validators.minLength(3), this.validateUserName.bind(this)]]
值改变事件:
let userNameControl = this.individualForm.get('userName');
userNameControl.valueChanges.subscribe(value => {
this.setErrorMessagesForUserNameControl(userNameControl)
}
);
验证函数:
validateUserName(control: FormControl): Promise<any> {
let promise = new Promise<any>(
(resolve, reject) => {
if (this.oldUserNameForCheck != undefined) {
this._individualUpdateService.isUserNameExisting(this.oldUserNameForCheck, control.value).subscribe(
(res) => {
if (res.isUserNameExisting) {
console.log("existing");
resolve({'existing': true});
} else {
console.log("NOT existing");
resolve(null);
}
},
(error) => {
console.log(error);
}
);
} else {
resolve(null);
}
}
);
return promise;
}
我只是尝试通过将用户名发送到后端来验证用户名。
如您所见,有一条“required”、“minlength”消息。那些工作正常。但是自定义验证的消息不是很清楚。
【问题讨论】:
标签: validation angular asynchronous