0

Possible Duplicate:
Validate email address in Javascript?
Validate email with jQuery

Currently I am using this in a contact form that I have built to check that the email field is not left blank

    var email = $("input#email").val();  
            if (email == "") {  
            $("label#email_error").show();  
            $("input#email").focus();  
        return false;  
        }

How can I run a check that the email input field contains an @ character?

Community
  • 1
  • 1
Andy
  • 1,422
  • 5
  • 27
  • 43
  • 1
    possible duplicate of [Validate email with jQuery](http://stackoverflow.com/questions/5778624/validate-email-with-jquery) and [How to validate textbox for emailid using JQuery?](http://stackoverflow.com/questions/6277513/how-to-validate-textbox-for-emailid-using-jquery). – Felix Kling Feb 19 '12 at 13:59

2 Answers2

1

Change if (email == "") { to if (!(email.indexOf('@') > 0)) {. This will make sure that:

  • The string contains @.
  • The @ is not the first character.
  • The string is not empty.

Example:

var email = $("input#email").val();
if (!(email.indexOf('@') > 0)) {
    $("label#email_error").show();
    $("input#email").focus();
    return false;
}
James M
  • 18,506
  • 3
  • 48
  • 56
pete
  • 24,141
  • 4
  • 37
  • 51
  • I tried this but it didn't work. In fact, the form submitted when the field was blank. – Andy Feb 19 '12 at 18:29
  • I realize the logic error now. It needs to be NOT'd. Modified answer, please try again and let us know. – pete Feb 19 '12 at 18:35
0

How can I run a check that the email input field contains an @ character?

Simple enough:

if(email.indexOf('@') == -1)
{
    /* no @ in the string */
}

This is not enough to validate an email address, however. See the previous question: Validate email address in JavaScript?

Community
  • 1
  • 1
James M
  • 18,506
  • 3
  • 48
  • 56