Email validation using Javascript
Email validation using Javascript
Email validation using Javascript
Simple script that validate email address using javascript. This is very much useful for login and contact forms which can validate the email address that are entered by the users. Grab the javascript function that is used for validation from below.
function checkEmail(email) {
var str = new String(email);
var isOK = true;
rExp = /[!\"£$%\^&*()-+=<>,\'#?\\|¬`\/\[\]]/
if( rExp.test(str) )
isOK = false;
if( str.indexOf('.') == -1 || str.indexOf('@') == -1 )
isOK = false;
if( str.slice(str.lastIndexOf('.')+1,str.length).length < 2 )
isOK = false;
if( str.slice(0,str.indexOf('@')).length < 1 )
isOK = false;
if( str.slice(str.indexOf('@')+1,str.lastIndexOf('.')).length < 1 )
isOK = false;
if((str.slice(str.indexOf('@'),str.indexOf('.')).length) <2)
isOK = false;
if( !isOK )
{
alert( "Invalid email address" );
document.getElementById('btnAdd').disabled = 'true';
}
else
{
document.getElementById("btnAdd").disabled = false;
alert("Looks Like A Valid Email Address");
return isOK;
}
}
Here the btnAdd is the ID of the submit button. The above script says if the entered email address is not valid then the Submit button will get disabled.
<input onChange="checkEmail(this.value)" size="50" type="text" id="txtEmail" name="txtEmail" /> <input class="loggedin" type="button" id="btnAdd" name="Send" value="Submit" onclick=""/>
In the html above i have given the onchange switch which is available inside the input tag. This will help us to validate the email address entered by the user when he click or focus the mouse button outside the email input field. Rest of the information in this script is self explanatory.