I'm making a really simple email validation script that basically just checks the following
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.
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. :)
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); }
Try:
function valid_email(email) {
return email.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i);
}
That is the best available email validation regex, according to this article. I recommend using this, unless your goal is something really simple but not fully compatible.