My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com

Pages










Tuesday, May 18, 2010

Javascript - Validate Email Address

An email Address constitute of following:

--A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores
--The at symbol @
--A combination of letters, numbers, hyphens, and/or periods. (Alphanumerics)
--A period
--The top level domain name (com, net, org, mobi, us, etc)


Some valid examples are:
•toughjamy@yahoo.com
•anwar.toughjamy@gmail.com
•mohdajf@adobe.com

Invalid Examples:
•@hahaha.net - no characters before the @
•cumon&dom@anwar.art - invalid character &
•buffalo@buffalo_univ.edu - underscores are not allowed in the domain name


For the purpose of email validation I employ regular expressions. The function validateEmailId would do the task for us, as follows:

function validateEmailId(element, alertMessage)
{/*Written by : Mohd Anwar Jamal Faiz 18 May 2008
Language : JavaScript

1. element is the Document element having email address , usually a textbox.
2. alertMessage would be the error message if email address is wrongly formed.

Note: Use of this function is free. But you must not remove the link to this blog.
*/
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(element.value.match(emailExp)){
return true;
}else{
alert(alertMessage);
element.focus();
return false;
}
}


You can use this function in conjugation with appropriate HTML code. For example there can be a webpage having a form as follows:





* Please note that I kept HTML in a remark tag. Or else, this page would have not contained code. Instead a real text box and button would have appeared. But this technique didnt work. So again I made a picture of the text and uploaded on blogger. There are many other ways which I will discuss, at some later time.

Till then, this was the tip of the day!!!

4 comments: