Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

jquery - Super simple email validation with javascript

I'm making a really simple email validation script that basically just checks the following

  1. that the email isn't blank
  2. the the email contains an @ symbol with at least 1 character before it
  3. that there is a domain ie @ with at least 2 letters after it
  4. 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.

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

 }

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.

Thanks for any tips.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...