我编写了一个web api函数,它从文本字段中获取用户名并检查是否已经使用了用户名。要知道用户名是否可用,我的服务器会返回Y
(如果可用)和N
(如果不可用)。
要验证用户名,我在Angular2中使用ValidatorFn,以验证输入。但是,我的验证器功能不起作用。
这是验证器功能:
interface Validator<T extends FormControl> {
(c: T): { [error: string]: any };
}
function validateUsername(c: string) : ValidatorFn {
return (this.isAvailable(c)=='Y') ? null : {
validateUsername: {
valid: false
}
};
}
这是isAvailable函数:
private isAvailable(username: string) {
let usernameAvailable;
let url = 'URL/api/auth/checkuser/' + username;
let headers = new Headers();
headers.append('User', sessionStorage.getItem('username'));
headers.append('Token', sessionStorage.getItem('token'));
headers.append('AccessTime', sessionStorage.getItem('AccessTime'));
let options = new RequestOptions({ headers: headers });
this.http.get(url, options)
.subscribe((res: Response) => usernameAvailable);
return usernameAvailable; //returns Y or N
}
表单构建器:
complexForm: FormGroup;
constructor(private http: Http, fb: FormBuilder) {
this.complexForm = fb.group({
'username': [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10), validateUsername(this.complexForm.controls['username'].value)])],
})
}
validateUsername(this.complexForm.controls['username'].value)
失败了,我收到了这个错误:
[ts] Type '{ validateUsername: { valid: boolean; }; }' is not assignable to type 'ValidatorFn'. Object literal may only specify known properties, and 'validateUsername' does not exist in type 'ValidatorFn'. (property) validateUsername: {
valid: boolean;
}
答案 0 :(得分:3)
您没有正确添加验证器功能。注册时,您不需要调用您的函数:
this.complexForm = fb.group({
'username': [null, Validators.compose(
[
Validators.required,
Validators.minLength(5),
Validators.maxLength(10),
validateUsername <----- don't call it here
]
)],
})
您可以看到一些函数被调用:
Validators.minLength(5),
但那是工厂函数调用而不是验证器函数调用。在初始化期间,他们返回ValidatorFn
:
/**
* Validator that requires controls to have a value of a minimum length.
*/
static minLength(minLength: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
...
}
查看更多in the official docs。
此外,您的验证器似乎是异步的,因此您必须在异步数组中传递它。而且我认为你不需要Validators.compose
。因此,正确的配置应如下所示:
this.complexForm = fb.group({
'username': [null, [
Validators.required,
Validators.minLength(5),
Validators.maxLength(10),
], [validateUsername]]
})
关于错误:
输入&#39; {valid:boolean; }&#39;不能分配给
ValidatorFn
类型。
您需要使用正确的返回类型ValidationErrors
而不是ValidatorFn
:
function validateUsername(c: string) : ValidationErrors {
return (this.isAvailable(c)=='Y') ? null : {
validateUsername: {
valid: false
}
};
}