【问题标题】:Custom email validation with angular使用 Angular 自定义电子邮件验证
【发布时间】:2020-02-23 19:18:35
【问题描述】:

我正在尝试实现自定义角度函数来验证电子邮件地址, 一切都很好,除了当我输入 example@mail 时,验证不起作用,它认为电子邮件的地址是有效的

验证器.ts


  static emailsLenghtAndFormat(control: AbstractControl): ValidationErrors | null {
    const email = control.value;
    const responseKo = { invalid: true };
    const responseOk = null;
    const responseKoMaxLength = { maxlength: true };

    if (!email) {
      return responseOk;
    }

    if (email.length > 100) {
      return responseKoMaxLength;
    }

    const EMAIL_REGEXP = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

    if (email !== '' && (email.length <= 5 || !EMAIL_REGEXP.test(email))) {
      return responseKo;
    }

    return responseOk;
  }

authent.ts

      this.formAuthentification = this.fb.group({
        authentification: this.fb.group(
          {
            email: ['', [Validators.required, Validators.email, Validators.maxLength(100)]],
            password: ['', Validators.required],
          },

        {
          validator: [ValidatorsCustom.emailsLenghtAndFormat]
        }
        )
      });

【问题讨论】:

  • 实际上只有一种方法可以验证电子邮件 - 向该地址发送内容并等待回复。

标签: angular angular-reactive-forms angular-forms email-validation


【解决方案1】:

您正在检查整个表单组。在这种情况下,您的输入不是 AbstractControl,而是一个表单组。然后它将字符串化您的表单组并尝试在整个字符串化的表单组中找到正则表达式。

static emailsLenghtAndFormat(group: FormGroup): ValidationErrors | null {
    const email = group.get('email').value;
    const responseKo = { invalid: true };
    const responseOk = null;
    const responseKoMaxLength = { maxlength: true };

    if (!email) {
      return responseOk;
    }

    if (email.length > 100) {
      return responseKoMaxLength;
    }

    const EMAIL_REGEXP = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

    if (email !== '' && (email.length <= 5 || !EMAIL_REGEXP.test(email))) {
      return responseKo;
    }

    return responseOk;
  }

【讨论】:

  • 我删除了 Validators.email 和 Validators.maxLength(100) 它变成了 email: ['', [Validators.required,ValidatorsCustom.emailsLenghtAndFormat]] 并且它工作了感谢您的回复:)
  • 将此标记为答案,如果解决了您的问题,请点赞;)
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 2020-10-20
  • 2012-01-03
相关资源
最近更新 更多