Last updated on March 13th, 2022 at 05:40 pm

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 to validate email address from below.

<script>
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;
}
}
	</script>

Here btnAdd is the ID of the submit button.

This is the regex for verifying any extra characters and if that is the case it says “Invalid email address

rExp = /[!\"£$%\^&*()-+=<>,\'#?\\|¬`\/\[\]]/
if( rExp.test(str) )
isOK = false;

This section of the script will make sure that email address is in the right format.

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';
}

This script also has the ability of disabling the button automatically if the email address is invalid.

<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 provided the OnChange switch which is added inside the input tag. This will help us to validate the email address entered by the user when they click or focus the mouse button outside the email input field. Rest of the information in this script is self explanatory.

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *