Thursday, April 30, 2009

Email syntax validation using javascript


We should validate the syntax of email entered in the form in the client side itself to save unnecessary server process to validate the email.

It can be done using javascript.
Consider below form.
onSubmit event of Form is calling a javascript function ValidateForm


<form name="frmSample" method="post" action="" onSubmit="return ValidateForm();">
<p>Enter an Email Address :
<input type="text" name="txtEmail">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>



The javascript function ValidateForm is calling another function emailcheck to validate syntax of the email id.


<script language = "Javascript">

function emailcheck(str) {

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1){

return false //if @ symbol is not there
}

if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){

return false //if @ symbol available at starting or ending of email.
}

if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){

return false //if "." is not available, or available at beginning or end of email.
}

if (str.indexOf(at,(lat+1))!=-1){

return false //if more one @ symbol available in email
}

if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){

return false //if no letter is available between @ and "."
}

if (str.indexOf(dot,(lat+2))==-1){

return false
}

if (str.indexOf(" ")!=-1){

return false //if blank space available in email.
}

return true
}

function ValidateForm(){
var emailID=document.frmSample.txtEmail

if ((emailID.value==null)||(emailID.value=="")){
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (emailcheck(emailID.value)==false){
emailID.value=""
emailID.focus()
return false
}
return true
}
</script>

More Articles...

1 comment:

Aravinth said...

In case to check whether the symbols like /:; are avail
how to validate the email

Search This Blog