简体   繁体   English

如何在Angular2 / 4/5中实现自定义异步验证器

[英]How to implement Custom Async Validator in Angular2/4/5

1. Is it even supported by Angular yet ? 1.它甚至得到了Angular的支持吗? see this open issue 看到这个开放的问题

2. If it is, then what is wrong in the code below 2.如果是的话,什么是错在下面的代码

export class someClass{

    myForm:ControlGroup;

    constructor(public http:Http, public formBuilder:FormBuilder)
       this.myForm = formBuilder.group({
            ImageId: ["", Validators.required, this.asynValidator]
    });

    asyncValidator(control: Control): {[key: string]: any} {

        return new Promise (resolve => {

          let headers = new Headers();
          headers.append('Content-Type', 'application/json');

          this.http.get('http://localhost/ImageIdValidate?id='+ control.value, {headers:headers})
                .map(res => res.json())
                .subscribe(data => {
                    console.log(data);
                    if(data != null) {
                        resolve({"duplicate": true})
                    }
                    else resolve(null);      
                })
            });
        });
      }
    }

It doesn't even make a server request. 它甚至没有提出服务器请求。

You need to bind your method on the component instance itself as described below: 您需要在组件实例本身上绑定您的方法,如下所述:

this.myForm = formBuilder.group({
            ImageId: ["",    
               Validators.required, 
               this.asynValidator.bind(this)]
    });

Otherwise you won't be able to use the http property to execute your request. 否则,您将无法使用http属性来执行请求。

This article could also give you some hints about asynchronous form validation (see the section "asynchronous validation"): 本文还可以为您提供有关异步表单验证的一些提示(请参阅“异步验证”一节):

as of newer versions of Angular, but pre version 5.0.0 you would add the async validator as the third argument for your formcontrol: 从更新版本的Angular开始,但在5.0.0之前的版本中,您可以添加异步验证器作为formcontrol的第三个参数:

myControl: ['', [Validators.required], [this.asyncValidator.bind(this)]]

since version 5.0.0 you can now mark the validators like so: 从版本5.0.0您现在可以像这样标记验证器:

myControl: ['', {validators: [Validators.required], 
                 asyncValidators:[this.asyncValidator.bind(this)]}]

Hello guys thanks for the solution. 大家好,谢谢你的解决方案。 However it didnt work for me outta the box. 然而它对我来说不起作用。

the problem was the async validator had to be a next parameter as part of the validators. 问题是异步验证器必须是验证器的一部分的下一个参数。 so what worked for me was 对我有用的是

this.myForm = formBuilder.group({
        ImageId: ["",    
           [Validators.required], 
           [this.asynValidator.bind(this)]]
});

and tadaa!! 和tadaa !! the headache was gone. 头痛不见了。 hope it helps someone. 希望它可以帮到某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM