我正在使用响应式(Reactive)表单来获取用户输入。对我正在使用的模式的 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
--> 没有错误
我在多个在线正则表达式测试器中检查了这个正则表达式,他们都只接受上面最后一个例子,他们都不接受第二个。
编辑:
正则表达式很好并且运行良好,问题是模式验证器以某种方式没有正确解析正则表达式,或者其他什么。
最佳答案
模式不正确 string .事实上,你在一个字符串中,所以要逃避“。”您需要使用双反斜杠,例如:
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.3 和 3.4.1 部分)和 RFC 5321 )。例如 email validator 中的 Angular 构建使用以下模式
/^(?=.{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])?)*$/
关于javascript - 正则表达式的 Angular 4 react 形式电子邮件验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49175054/