我使用 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();
您有更好的想法来达到相同的验证吗?关于这个问题的任何最佳实践?
谢谢你。