繁体   English   中英

Angular 4 反应式表单电子邮件验证通过正则表达式失败

[英]Angular 4 reactive form Email validation by regular expression fail

我正在使用反应式表单来获取用户输入。 对我使用的模式不满意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 --> 没有错误

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

编辑:
正则表达式很好并且运行良好,问题是模式验证器以某种方式没有正确解析正则表达式,或者其他什么。

该模式作为字符串不正确。 实际上你在一个字符串中,所以要转义 '.' 你需要使用双反斜杠,如:

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

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

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

编辑:请记住,这是一个简单的模式,它排除了许多有效的电子邮件地址(请参阅 RFC 5322(第3.2.33.4.1节)和 RFC 5321 )。 例如,电子邮件验证器中的角度构建使用以下模式

/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/

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

像这样导入:

import { CustomValidators } from 'ng2-validation';

并在您的表单控件中使用它:

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

问候,

我用这个:

/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/ 
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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM