0

it looks very basic thing but i could not figure it out.

var email = $("input#email").val();

how can i check if that email variable has @ letter ?

Thanks

Utku Dalmaz
  • 9,780
  • 28
  • 90
  • 130

2 Answers2

5

Or instead of regex, use the correct tool: indexOf()

var hasAtCharacter = (email.indexOf('@') != -1);
Amy B
  • 17,874
  • 12
  • 64
  • 83
  • Correct with respect to the question, but a really bad way to validate email addresses -- @@@@@@@@@ is not a valid email address. – tvanfosson Mar 23 '10 at 14:55
3

Use the string.match() method to check if it matches a regular expression containing @. You probably want to use a better expression to validate that it's an email address, though.

var email = $("input#email").val();
var isEmail = email.match( /@/ );

Or you can use a regular expression and the test method.

 var email = $('input#email').val();
 var re = new RegExp( '^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$' );
 if (re.test(email)) {
    ...
 }

Note - I have no idea if that regex is what you need, you might want to do some research into email validators to see if that's adequate or you want to improve on it.

Alternatively, you could look at using the jQuery validation plugin. It's validation methods include email addresses.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795