Angular2:电子邮件已作为自定义验证程序存在?

时间:2017-01-25 09:01:50

标签: validation angular typescript angular2-forms reactive-forms

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

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;
            });
    }
}

要启用模板文件中的“提交”按钮,我会检查myForm.valid并将found设置为false

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

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

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

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

谢谢。

1 个答案:

答案 0 :(得分:1)

哇。这远远不是反应形式验证的想法。

首先不要这样做

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

setValidatorsupdateValueAndValidity是您几乎从不打电话的功能。它们仅适用于某些特定情况,如动态表单行为。

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

在一天结束时你应该

...
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
      });
    })
  });
}
...

那就是它。