首页 文章

Angular 4反应形式正则表达式的电子邮件验证失败

提问于
浏览
2

我正在使用反应式表单来获取用户输入 . 不满意 EmailValidator 我正在使用模式 .

emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
this.email = new FormControl('', [Validators.required, Validators.pattern(emailRegEx)]);

和HTML:

<input type="email" formControlName="email" [ngClass]="contactForm.get('email').errors && (contactForm.get('email').dirty || isButtonClicked) ? 'contact-input input-error' : 'contact-input'">

但这就是事情,由于某种原因,正则表达式在 @ 之后接受4个字符,没有句号 . name@d - >错误
name@doma - >没有错误
name@domain. - >错误
name@domain.com - >没有错误

我在多个在线正则表达式测试器中检查了这个正则表达式,他们都只接受上面的最后一个例子,他们都没有接受第二个例子 .

编辑:
正则表达式很好并且运行良好,问题是模式验证器不能正确地解析正则表达式或其他东西 .

3 回答

  • 3

    该模式不正确string . 在 Contract 中你是一个字符串,所以要逃避'.'你需要使用双反斜杠,如:

    emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'
    

    或者如果你想避免这样做,我建议使用:

    emailRegEx = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/
    
  • 0

    您可以使用提供过多类型验证的CustomValidator包:https://www.npmjs.com/package/ng2-validation

    像那样导入它:

    import { CustomValidators } from 'ng2-validation';
    

    并在表单控件中使用它:

    this.email = new FormControl('', [Validators.required, CustomValidators.email]);
    

    问候,

  • 1
    import {Component} from '@angular/core';
    import {FormBuilder, FormGroup, Validators} from '@angular/forms';
    
    @Component({
        templateUrl: './forgot-password.component.html',
        styleUrls: ['./forgot-password.component.scss']
    })
    export class ForgotPasswordComponent {
    
        psResetForm: FormGroup;
    
        constructor(private fb: FormBuilder) {
            this.psResetForm = fb.group({
                'email': [null, Validators.compose([Validators.required, Validators.email])]
            });
        }
    
        makeRequestToResetLink(formData, valid: boolean) {
            if (valid) {
                alert(formData.email);
            }
        }
    
    }
    

    您的模板应如下所示

    <form [formGroup]="psResetForm" (ngSubmit)="makeRequestToResetLink(psResetForm.value,psResetForm.valid)">
        <input type="email" formControlName="email"/>
        <button type="submit">
            submit
        </button>
    </form>
    

相关问题