user2837585
user2837585

Reputation: 3

Email validation not working correctly using javascript

This is my email address validation code using JavaScript. The alert messages are correctly working but when I submit giving a valid email address it alerts 'Please provide a valid email address'. Please help me.

if(email=="")
{
    alert("Enter emailid");
    $("#email").focus();
    return false;
}

else if(email!="")
{
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email.value)) 
    {   
        //alert(email)
        //alert(filter.test(email.value)) 
        alert('Please provide a valid email address');
        email.focus();
        return false;
    }
}

Upvotes: 0

Views: 2819

Answers (3)

nrsharma
nrsharma

Reputation: 2562

Try this

function ValidateEmail(){

var email = $('#txtemail').val();
if(email=="")
{
    alert("Enter emailid");
    $("#txtemail").focus();
    return false;
}

else if(email!="")
{
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email)) 
    {   
        //alert(email)
        //alert(filter.test(email.value)) 
        alert('Please provide a valid email address');
        $('#txtemail').focus();
        return false;
    }
}
}

Call the function ValidateEmail on the onclick event of your button. And also please note that you are doing something wrong with this line

if (!filter.test(email.value)) 

change this to be

if (!filter.test(email)) 

hope this helps.

Working DEMO

Upvotes: 0

bubi
bubi

Reputation: 117

There is a small mistake in your code, which makes the alert to display.

Please look for this line in your code

if (!filter.test(email.value)) 

and replace with

if (!filter.test(email)) 

Variable Email holds the value of Email field of your form.

And another change would be, look for this line

email.focus();

and change this one to

$("#email").focus();

Upvotes: 0

Zero
Zero

Reputation: 738

Not a direct answer to your question...but can you not use HTML5 email input for this purpose? Why write javascript code for email validation when the browser can handle it? Use something like this:

<input type="email" name="email">

There are many advantages to using this including on-screen keyboard to match it (adds @ and .com options).

For different types of HTML5 input types, refer this: http://www.w3schools.com/html/html5_form_input_types.asp

Upvotes: 1

Related Questions