Tomer
Tomer

Reputation: 17930

Regular expression test not working properly

I'm trying to write a simple RegExp that would validate a login name:

function _validateLogin( login ) {
   //This should allow for [a-zA-Z0-9_] as well as '.' and '@'
   //Spaces are not allowed
   var re = /[\w\.@]+/;
   return re.test( login );
}

But for some reason it returns true even if I give it 'aa aa'. What am i doing wrong?

Upvotes: 0

Views: 169

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Change your regex to ^[\w.@]+$ to match with entire string. I case aa aa it will return true , since aa will match . So use ^ at beginning for assert position at beginning of a string and $ at end for assert position at end of the string. Also there is no need for escape ., since dot doesn't have any have special meaning inside a character class.

function _validateLogin(login) {
  //This should allow for [a-zA-z0-9_] as well as '.' and '@'
  //Spaces are not allowed
  var re = /^[\w.@]+$/;
  return re.test(login);
}

console.log(_validateLogin('aa aa'));
console.log(_validateLogin('aaaa'));

Upvotes: 1

melpomene
melpomene

Reputation: 85767

You're not anchoring the regex. It will return true for any string that contains a letter, digit, underscore, dot, or at sign anywhere.

Fix: var re = /^[\w.@]+$/;

Upvotes: 1

Related Questions