1

我使用 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.validfound设置为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();

您有更好的想法来达到相同的验证吗?关于这个问题的任何最佳实践?

谢谢你。

4

1 回答 1

1

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

首先不要这样做

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

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

在您的情况下,您有一个静态表单,您应该用一些验证器来描述它。创建一个自定义异步验证器并将其分配给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
      });
    })
  });
}
...

就是这样。

于 2017-01-25T09:25:35.507 回答