使用服务器进行表单验证

时间:2017-01-28 13:42:19

标签: angular typescript

我有一个表单,我想通过检查电子邮件是否存在但是它返回错误来执行http验证。这是我的表格:

在表单组件

 constructor(
   private _formBuilder:FormBuilder,
    private _validationService:ValidationService
  ) { }

 ngOnInit() {
this.resetForm = this._formBuilder.group({
  email:['',Validators.compose([
    this._validationService.emailExistsValidator  //this returns an error
   ,Validators.required
  ])]
})

在validationService

  constructor(
public _authService:AuthService  //tried also with private
 ){}

  emailExistsValidator(control){
  if(control.value != undefined) {
  this._authService.checkExists("email")
      .map(response => {
        if (!response) {
           return {'emailNotExists': true};
        }
      });
   }
}

在_authservice(它的服务)

checkExists(value:string):Observable<any>{
return this._httpclient.get(this.authurl+value)  //httpclient attches the headers
  .map(response => {
   return response
  });
}

现在收到此错误

Argument of type '((control: any) => void)[]' is not assignable to4
 parameter of type 'ValidatorFn[]'.
  Type '(control: any) => void' is not assignable to type 'ValidatorFn'.
Type 'void' is not assignable to type '{ [key: string]: any; }'.)

我还需要做些什么?

1 个答案:

答案 0 :(得分:2)

https://angular.io/docs/ts/latest/api/forms/index/FormBuilder-class.html

async validators是第3个参数

email:['', [Validators.required], [
  this._validationService.emailExistsValidator.bind(this)
]]