0

我是 Angular 的新手,我创建了一个自定义 EmailDomainError 验证器类并且它工作正常。

但问题是电子邮件域错误与电子邮件验证错误消息一起显示我该如何解决这个问题我真的很困惑有人可以帮助我吗

我想我必须在我的 EmailDomainError 类中检查电子邮件模式是否正确,我该如何检查?如果我认为正确的方法和我的完整代码--- https://stackblitz.com/edit/angular-bvihqj

ngOnInit

 ngOnInit() {

    this.employeeForm = this.fb.group({
      fullName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(10)]],
      contactPreference: ['email'],
      email: ['', [Validators.required, Validators.email, emailDomainError]],
      phone: [''],
      skills: this.fb.group({
        skillName: ['', [Validators.required]],
        experienceInYears: ['', [Validators.required]],
        proficiency: ['', [Validators.required]]
      })
    });

此对象包含此表单的所有验证消息

 formErrors = {
    'fullName': '',
    'email': '',
    'phone': '',
    'skillName': '',
    'experienceInYears': '',
    'proficiency': ''
  };


     validationMessages = {
        'fullName': {
          'required': 'Full Name is required.',
          'minlength': 'Full Name must be greater than 2 characters.',
          'maxlength': 'Full Name must be less than 10 characters.'
        },
        'email': {
          'required': 'Email is required.',
          'email': 'Valid Email id is required.',
          'emailDomainError': 'Email domain should be karvy.com'
        },
        'phone': {
          'required': 'Phone number is required.'
        },
        'skillName': {
          'required': 'Skill Name is required.',
        },
        'experienceInYears': {
          'required': 'Experience is required.',
        },
        'proficiency': {
          'required': 'Proficiency is required.',
        },
      };

电子邮件域错误

function emailDomainError(control: AbstractControl): { [key: string]: any } | null {
  const email: string = control.value;
  const domain: string = email.substring(email.lastIndexOf("@") + 1);
  if (email === '' || domain === "karvy.com") {
    return null;
  } else {
    return { "emailDomainError": true };
  }
}

在此处输入图像描述

4

1 回答 1

1

嗨 AbhiRam 我在这里更新你的代码是这里的链接

在表单组中更新这样的

email: ['', [Validators.required, emailError, emailDomainError]],

功能代码更改如下 *

*
 * emailDomainValidations
 * @param control 
 */

function emailDomainError(control: AbstractControl): { [key: string]: any } | null {
  const email: string = control.value;
  if (email && email.indexOf("@") != -1) {
    let [_, domain] = email.split("@");
    if (domain !== "karvy.com") {
      return {
        "emailDomainError": true,
       // "email": false
      };
    }

    else {
      return null;
    }
  }
}
function emailError(control: AbstractControl): { [key: string]: any } | null {
  const email: string = control.value;

  if( email.length <3 && email.length >=1){
    return { "email" : true}
  }
  else{
    return null;
  }

}
于 2018-11-29T13:09:55.073 回答