使用JavaScript进行超级简单的电子邮件验证 [英] Super simple email validation with javascript
问题描述
我正在制作一个非常简单的电子邮件验证脚本,基本上只是检查以下
I'm making a really simple email validation script that basically just checks the following
- 电子邮件不是空白
- 电子邮件中包含一个至少包含1个字符的@符号
- 有一个域名,即@后面至少有2个字母
- 它以一个至少包含2个字母的完整停止结束
- that the email isn't blank
- the the email contains an @ symbol with at least 1 character before it
- that there is a domain ie @ with at least 2 letters after it
- that it ends with a fullstop with at least 2 letters after it
我知道有很多更多检查,但我看看这些正则表达式规则,我的思想停止工作。我想如果我开始使用这样的小东西,我可能会围绕更复杂的规则。
I know there are many more checks, but I look at these regex rules and my mind stops working. I figure if I started with something small like this I might be able to wrap my brain around more complex rules.
目前使用一些jquery我会做以下事情:
Currently using some jquery I do the following:
var booking_email = $('input[name=booking_email]').val();
if(booking_email == '' || booking_email.indexOf('@') == -1 || booking_email.indexOf('.') == -1) {
// perform my alert
}
这足以到目前为止,停止90%的虚假电子邮件......我只是想让它更有效,因为目前我的规则将允许电子邮件,如'@ domain.com'或'user @ domain。',因为它只会检查是否存在一个fullstop和一个@符号。
This is enough to stop 90% of bogus emails so far... I would just like to make it a bit more effective because currently my rule will allow emails like '@domain.com' or 'user@domain.' because it only checks that there is a fullstop and an @ symbol.
感谢您的任何提示。
推荐答案
其他人的建议应该可以正常工作,但如果你想保持简单,试试这个:
What others have suggested should work fine, but if you want to keep things simple, try this:
var booking_email = $('input[name=booking_email]').val();
if( /(.+)@(.+){2,}\.(.+){2,}/.test(booking_email) ){
// valid email
} else {
// invalid email
}
即使你决定选择更强大的东西,它也应该有助于你理解正则表达式有时是多么简单。 :)
Even if you decide to go with something more robust, it should help you understand how simple regex can be at times. :)
这篇关于使用JavaScript进行超级简单的电子邮件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!