0

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;
    }
}
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
user2837585
  • 3
  • 1
  • 4

3 Answers3

1

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

Zero
  • 728
  • 1
  • 7
  • 15
  • 2
    Please, do not quote w3schools. It is known to be inaccurate. See http://www.w3fools.com/. – Étienne Miret Oct 03 '13 at 11:25
  • @EtienneMiret Read this: http://meta.stackexchange.com/questions/120621/w3fools-alternatives – Zero Oct 03 '13 at 11:29
  • I was linking you to w3fools, not the OP, so next time you link to a better resource. But OK, for completeness, let me link to the [HTML5 Specification](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#attr-input-type) about different input types. – Étienne Miret Oct 03 '13 at 11:59
0

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();
bubi
  • 105
  • 3
  • 12
0

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

nrsharma
  • 2,532
  • 3
  • 20
  • 36