Utku Dalmaz
Utku Dalmaz

Reputation: 10172

finding a letter in a string with jquery

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

Upvotes: 0

Views: 380

Answers (2)

Amy B
Amy B

Reputation: 17977

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

var hasAtCharacter = (email.indexOf('@') != -1);

Upvotes: 5

tvanfosson
tvanfosson

Reputation: 532465

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.

Upvotes: 3

Related Questions