0

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?

2 Answers 2

1

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'));

Sign up to request clarification or add additional context in comments.

Comments

1

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.@]+$/;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.