0
$.validator.addMethod('username', function (value) {
    return [A-Za-z0-9\-\_]+.test(value);
}, 'Username can only contain letters, numbers, underscores and dashes.');

I am no good with regular expressions OR jQuery/JavaScript which makes this almost impossible for me.

I simply want to add a method to validate a username to make sure it only has numbers, letters, underscores, and dashes (no spaces, periods, etc) but I can't seem to get it right.

Any help would be appreciated.

1
  • javascript regular expression literals must be surrounded by /.../. Commented Oct 31, 2012 at 19:45

2 Answers 2

2

There are two problems here. One, the regex needs delimiters. Two, the regex does not check whether the whole string is made up of those letters:

var regex = /^[\w-]+$/;
return regex.test(value);

I also shortened the regex a bit (the character class is the same).

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

Comments

0

You want to change your code to:

return (value.match(/^[A-Za-z0-9-_]+$/));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.