Saturday, October 20, 2012

Email validation in Javascript

We can check whether an given email address is ok or not through the regular expression show below.

<script type='text/javascript'>
// RegExp Pattern
var pattern = /^[a-zA-Z]+[a-zA-Z0-9_]*@[A-Z0-9a-z]+(\.){1,1}[a-zA-Z]{2,3}$/ ;


// Email to check
var email = "a@a.com";

// Show the result
console.log( pattern.test(email) );
</script>

The above code will print 'true' in your browser console. Let's dissect the regular expression to understand it more clearly.

1. ^[a-zA-Z]+     => means, the Input must start with character a through z in small/capital letters
2.[a-zA-Z0-9_]*  => means, characters and digits and underscore may or may not appear next. 
3. @         => '@' character must appear next
4. [A-Z0-9a-z]+  => means, character, digits will appear next, minimum 1 character/digit is must
5. (\.){1,1} => then, there must be a dot (.)... {1,1} means minimum 1 times and maximum 1 times respectively
6. [a-zA-Z]{2,3}$  => means, a series of character,digits will appear at the end of the input, but that series will have minimum 2 and maximum 3 characters/digits

No comments: