Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 674
willdanceforfun Avatar asked Feb 11 '11 01:02

willdanceforfun


People also ask

Can JavaScript be used for validation?

JavaScript provides the facility to validate the form on the client-side so data processing will be faster than server-side validation. It is preferred by most of the web developers. Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.


2 Answers

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

like image 98
Ashley Williams Avatar answered Oct 04 '22 14:10

Ashley Williams


The least possible greedy validation you an do is with this RegExp /^\S+@\S+\.\S+$/

It will only ensure that the address fits within the most basic requirements you mentioned: a character before the @ and something before and after the dot in the domain part (\S means "anything but a space"). Validating more than that will probably be wrong (you always have the chance of blacklisting a valid email).

Use it like this:

function maybeValidEmail (email) { return /^\S+@\S+\.\S+$/.test(email); } 
like image 42
gonchuki Avatar answered Oct 04 '22 15:10

gonchuki