Angular2:电子邮件已作为自定义验证器存在? [英] Angular2: email already exist as custom Validator?

查看:25
本文介绍了Angular2:电子邮件已作为自定义验证器存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Angular2 创建了一个表单,并创建了以下方法来检查电子邮件地址是否已存在.这是我的代码:

checkEmail(): void {//第一部分this.found = false;//如果用户不是高级用户...如果(!this.currentUser.isPremium){//...如果用户在输入字段中输入了一些内容,则为电子邮件地址应用验证器如果(this.myForm.controls.email.value.length > 0){this.myForm.controls.email.setValidators([validateEmail()]);this.myForm.controls.email.updateValueAndValidity();//如果用户将输入字段留空或将键入的输入清空,则应用所需的验证器} 别的 {this.myForm.controls.email.setValidators([Validators.required]);this.myForm.controls.email.updateValueAndValidity();}//如果用户是高级用户...} else if (this.currentUser.isPremium) {//...如果用户在输入字段中输入了一些内容,则为电子邮件地址应用验证器如果(this.myForm.controls.email.value.length > 0){this.myForm.controls.email.setValidators([validateEmail()]);this.myForm.controls.email.updateValueAndValidity();//如果用户将输入字段留空或清空键入的输入,则删除任何验证器} 别的 {this.myForm.controls.email.setValidators(null);this.myForm.controls.email.updateValueAndValidity();}}//第二部分//如果输入字段有效,则检查电子邮件是否已存在于服务器上...如果(this.myForm.controls.email.value.length > 0 && this.myForm.controls.email.valid){this.loadingIcon = true;this.anagraficaService.getEmail(this.myForm.controls.email.value).then(响应 => {让计数 = response.recordCount;如果(计数> 0){this.found = true;} 别的 {this.found = false;}this.loadingIcon = false;}).catch(错误=> {this.found = false;this.loadingIcon = false;});}}

为了在模板文件中启用提交按钮,我检查 myForm.validfound 设置为 false:

现在,我想检查电子邮件地址是否已经存在,我的意思是将我的代码的第二部分放在一个外部文件(自定义验证器)中,然后仅在我的代码的第一部分检查电子邮件地址的有效性.像这样:

this.myForm.controls.email.setValidators([validateEmail(), checkEmailExists()]);this.myForm.controls.email.updateValueAndValidity();

您有更好的想法来达到相同的验证吗?关于此问题的最佳做法是什么?

谢谢.

解决方案

哇.这与反应式表单验证的想法相去甚远.

首先不要这样做

this.myForm.controls.email.setValidators([validateEmail()]);this.myForm.controls.email.updateValueAndValidity();

setValidatorsupdateValueAndValidity 是您几乎不应该调用的函数.它们仅适用于某些特定情况,例如动态表单行为.

在您的情况下,您有一个静态表单,您应该使用一些验证器描述.创建自定义异步验证器并将其分配给 email FormControl.这个验证器应该返回一个 Observable(或一个 Promise),当一切正常时它解析为 null 或一个有错误的对象,例如{ emailAlreadyExists: true } 如果电子邮件存在,{ required: true } 或使用 Validators.required 和您的自定义异步验证的组合.

归根结底你应该有

<预><代码>...公共 ngOnInit() {this.myForm = new FormGroup({电子邮件:new FormControl('', null, (control: FormControl) => {返回新的承诺((解决,拒绝)=> {//还添加这里是高级逻辑让 requiredValidationResult = Validators.required(control);如果(requiredValidationResult){解决(requiredValidationResult);//这将是 {required: true}返回;}//在这里调用您的服务器并调用//resolve(null) 以防万一//resolve({ emailExists: true }) 以防它存在});})});}...

就是这样.

I created a form with Angular2 and I created the following method to check if the email address already exist. Here is my code:

checkEmail(): void {
    // FIRST PART
    this.found = false;
    // If user is not Premium...
    if (!this.currentUser.isPremium) {
        //  ...and if user typed something in the input field, then apply validitor for email address
        if (this.myForm.controls.email.value.length > 0) {
            this.myForm.controls.email.setValidators([validateEmail()]);
            this.myForm.controls.email.updateValueAndValidity();
        // If user leaves the input field blank or empty the typed input, then apply validator for required
        } else {
            this.myForm.controls.email.setValidators([Validators.required]);
            this.myForm.controls.email.updateValueAndValidity();
        }
    // If user is Premium...
    } else if (this.currentUser.isPremium) {
        // ...and if user typed something in the input field, then apply validitor for email address
        if (this.myForm.controls.email.value.length > 0) {
            this.myForm.controls.email.setValidators([validateEmail()]);
            this.myForm.controls.email.updateValueAndValidity();
        // If user leaves the input field blank or empty the typed input, then remove any validator
        } else {
            this.myForm.controls.email.setValidators(null);
            this.myForm.controls.email.updateValueAndValidity();
        }
    }

    // SECOND PART
    // If the input field is valid then check if the email already exist on server...
    if (this.myForm.controls.email.value.length > 0 && this.myForm.controls.email.valid) {
        this.loadingIcon = true;
        this.anagraficaService.getEmail(this.myForm.controls.email.value)
            .then(response => {
                let count = response.recordCount;
                if (count > 0) {
                    this.found = true;
                } else {
                    this.found = false;
                }
                this.loadingIcon = false;
            })
            .catch(error => {
                this.found = false;
                this.loadingIcon = false;
            });
    }
}

To enable the Submit button in the template file, I check for myForm.valid and for found set to false:

<button type="submit" class="ui primary button" (click)="onSubmit()" [disabled]="!myForm.valid || found">Submit</button>

Now, i would like to check for email address if already exists, I mean put the second part of my code in an external file (custom Validator) and then check for email address validity only in the first part of my code. Something like this:

this.myForm.controls.email.setValidators([validateEmail(), checkEmailExists()]);
this.myForm.controls.email.updateValueAndValidity();

Do you have a better idea to reach the same verifications? Any best practice about this problem?

Thank you.

解决方案

Wow. That's far away from the idea of reactive forms validations.

First of all don't do this

this.myForm.controls.email.setValidators([validateEmail()]);
this.myForm.controls.email.updateValueAndValidity();

setValidators and updateValueAndValidity are the functions you should nearly never call. They are available only for some specific cases like dynamic form behaviour.

In your case you have a static form which you should just describe with some validators. Create a custom asynchronous validator and assign it to the email FormControl. This validator should return an Observable (or a Promise) which resolves either to null when everything is fine or to an object with an error, e.g. { emailAlreadyExists: true } if email exists, { required: true } or use a combination of Validators.required and your custom async validation.

In the end of the day you should have

...
public ngOnInit() {
  this.myForm = new FormGroup({
    email: new FormControl('', null, (control: FormControl) => {
      return new Promise((resolve, reject) => {
        // also add here is premium logic
        let requiredValidationResult = Validators.required(control);

        if (requiredValidationResult) {
          resolve(requiredValidationResult); // this will be {required: true}
          return;
        }

        // and here call your server and call
        //   resolve(null) in case it's fine
        //   resolve({ emailExists: true }) in case it's existing
      });
    })
  });
}
...

and that's it.

这篇关于Angular2:电子邮件已作为自定义验证器存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆