Javascript: How to validate email address with JavaScript?
Posted on 13. Jun, 2009 by Dragos in Coding, JavaScript & Ajax
Here’s a piece of code I found while I was browsing the JQuery UI pages to easily validate email addresses.
The code below represents a general validation function, that requires two parameters:1. the string value of an obkect and 2. the regular expression to check the string against
function checkRegexp(o,regexp) {
if ( !( regexp.test( o ) ) ) {
return false;
} else {
return true;
}
}
Now, here’s the following code to use in order to validate email addresses:
var regex=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
var first=checkRegexp("email@email.",regex); //boolean false, because the email address is missing the tld
var second=checkRegexp("email@email.tld",regex); //boolean true
It’s good to validate email addresses right on the client side, because you save server resources consumption and the client is also able to correct any errors faster, without reloading the page. But you should never avoid rechecking the email (and not only emails) on the server side.
Related posts:
- PHP: Script to extract one’s contacts from email (Gmail, Yahoo,Hotmail,AOL…) and send invites – OpenInviter to go!
- JavaScript: Get anchor from URL
- JavaScript: How to get the index (position within a group) of an object with jQuery?
- JavaScript: Where do I Find All Properties for All HTML Elements ?
- JavaScript: Send function as a parameter to another function (callbacks)
-
Hakkisaglam










































