我想检查用户输入是否是JavaScript的电子邮件地址,然后将其发送到服务器或试图发送电子邮件,以防止最基本的误解。
当前回答
一个很好的做法是验证客户端的数据,但双重检查服务器上的验证。 考虑到这一点,您可以简单地检查是否链接看起来像客户端的有效电子邮件地址,并在服务器上进行严格的检查。
下面是我使用的JavaScript功能来检查一个字符串是否看起来像一个有效的邮件地址:
function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('@');
var lastDotPos = str.lastIndexOf('.');
return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}
解释:
lastAtPos < lastDotPos: Last @ 应该是之前的最后. 因为 @ 不能是服务器名称的一部分(我知道的范围内)。 lastAtPos > 0: 应该是某些东西(电子邮件用户名)之前的最后 @. str.indexOf('@') == -1: 应该是没有 @@ 在地址. 即使 @ 出现在电子邮件用户名中的最后一个字符,它必须引用这样“ 会是 @ 和最后一个 @ 在地址。
其他回答
如果你把你的常规表达式定义为一个字符串,那么所有的背影都必须逃脱,所以而不是“\w”你应该有“\w”。
否则,将其定义为常规表达式:
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
<pre>
**The personal_info part contains the following ASCII characters.
1.Uppercase (A-Z) and lowercase (a-z) English letters.
2.Digits (0-9).
3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.**
</pre>
*Example of valid email id*
<pre>
yoursite@ourearth.com
my.ownsite@ourearth.org
mysite@you.me.net
xxxx@gmail.com
xxxxxx@yahoo.com
</pre>
<pre>
xxxx.ourearth.com [@ is not present]
xxxx@.com.my [ tld (Top Level domain) can not start with dot "." ]
@you.me.net [ No character before @ ]
xxxx123@gmail.b [ ".b" is not a valid tld ]
xxxx@.org.org [ tld can not start with dot "." ]
.xxxx@mysite.org [ an email should not be start with "." ]
xxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ]
xxxx..1234@yahoo.com [double dots are not allowed
</pre>
**javascript mail code**
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
如果你正在使用NG模式和材料,这就是工作。
vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))';
如果你得到这个错误:使用常规表达式是安全敏感的。
这个解决方案是免费的“定期表达拒绝服务(ReDoS)”
Regex 可验证无电子邮件(ReDoS):
/^[a-z0-9](?!.*?[^\na-z0-9]{2})[^\s@]+@[^\s@]+\.[^\s@]+[a-z0-9]$/
请告诉我这个解决方案是否适合你,谢谢。
我真的很高兴能解决这个问题,所以我修改了电子邮件验证的常规表达。
<unk> <unk> <unk> <unk> <unk> <unk> <unk> <unk>
在维基百科的电子邮件地址中提交例子。
你可以在这里看到结果。
此分類上一篇
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?