HandsomeRob
HandsomeRob

Reputation: 445

Regular Expression to validate email: illegal character

Doing form validation using Jquery without plugins, they're easy enough to use. Trying to teach myself regular expressions and at a wall.

var email = $('#email').val();

// Validate email address

// Regular expression to match email address:
var emailReg = \S+@\S+;

if(email.match(emailReg)) {
    // Pass
}
else {
    // Fail
    $('#email').css("background","yellow");
    var counter2 = setTimeout("$('#email').css('background','white')", 3000);
    return false;
}

I know it's the worlds simplest regular expression, just trying to get functionality and I'll get more sophisticated later.

Keep getting SyntaxError: illegal character \S (here) +@S+

Don't understand why. Have searched this site and tried dozens always with console errors.

Upvotes: 0

Views: 284

Answers (3)

Scott Wagner
Scott Wagner

Reputation: 36

Regular expressions are enclosed in forward slashes in js. Try var emailReg = /\S+@\S+/;

Upvotes: 0

RoneRackal
RoneRackal

Reputation: 1233

You need to place your regex in forwardslashes like so:

var emailReg = /\S+@\S+/;

This way it knows it's a regex object, instead of just random operators put together

You could also do:

var emailReg = new RegExp("\S+@\S+");

This method is useful if you aren't just writing a static regex (eg. getting the regex from user input)

Upvotes: 0

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

Add / around it.

var emailReg = /\S+@\S+/;
               ^       ^

Upvotes: 1

Related Questions