2017-04-12 54 views
2

我在我的项目中应用了Angular 4,并且在使用HTTP请求进行自定义验证时遇到了问题。如何在Angular4中实现自定义异步验证器

我也试试这个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; 
} 

Error Messages

我只是尝试通过将其发送到后端来验证用户名。

Here's the logs

正如你可以看到,有一个为 “必需的”, “使用MINLENGTH”,那些做工精细的消息。但是自定义验证的消息不是很清楚。我真的很感谢你的帮助,感谢先进的:)

回答

1

异步验证应该是在下一个参数

userName: ['', 
    [ Validators.required, Validators.minLength(3) ], 
    [ this.validateUserName.bind(this) ] 
] 

也是它最好有一个工厂方法,将创建验证所需的依赖,而不是用'绑定(本)'

userNameValidator(originalUsername, individualUpdateService) { 
    return (control: FormControl): Promise<any> => { 
     return new Promise<any>((resolve, reject) => { 
      if (originalUsername != undefined) { 
       individualUpdateService.isUserNameExisting(originalUsername, 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); 
      } 
     }) 
    } 
} 

userName: ['', 
    [ Validators.required, Validators.minLength(3) ], 
    [ this.userNameValidator(this.oldUserNameForCheck, this._individualUpdateService) ] 
] 
+0

感谢您的帮助,但它不起作用。 这里的日志打印在控制台上: https://www.dropbox.com/s/19acvswgf1951s9/2017-04-19_160732.jpg?dl=0 –

+0

我做到了这一点: userName:['',[Validators .required,Validators.minLength(3)],[this.validateUserName.bind(this)]], –

相关问题