我已经尝试了[angular2 async validation this.subscribe exception?的答案的每个排列,但我仍然得到例外。
import {AsyncValidatorFn, AbstractControl } from '@angular/forms';
export function userNameShouldBeUnique(): AsyncValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
return new Promise(resolve => {
setTimeout(() => {
if (control.value == 'mosh')
resolve({ shouldBeUnique: true });
else
resolve(null);
}, 1000);
});
}
}
并在组件中(最后一次尝试):
this.myForm = this.fb.group({
username: [
'',
Validators.compose([Validators.required, forbiddenNameValidator(/bob/)]),
Validators.composeAsync([userNameShouldBeUnique])
],
password: ['', Validators.required]
});
所以我做错了什么?感谢
答案 0 :(得分:1)
解决方案是:
import { AsyncValidatorFn, AbstractControl } from '@angular/forms';
export function UniqueValidator(): AsyncValidatorFn {
return (control: AbstractControl): Promise<any> => {
return new Promise<any>(resolve => {
setTimeout(() => {
if (control.value === 'mosh')
resolve({ shouldBeUnique: true });
else
resolve(null);
}, 1000);
});
};
};
现在您已经配置好了返回类型。要添加为自定义验证:
username: ['', Validators.required, UniqueValidator()]
刚刚测试过,它有效;)