I'm trying to validate a username field in my form via client-side valdiation and I'm having some trouble.
I'm trying to use match them against regexs, which seems to work for my password strength/match. However when I try and change the regular expression to one that is suitable for usernames it doesn't work.
This is the regular expression that works, it checks to see if the length is at least 6 chars long.
var okRegex = new RegExp("(?=.{6,}).*", "g");
This is the other regular expression which does not work:
var okRegex = new RegExp("/^[a-z0-9_-]{3,16}$/");
How do I write a regex that performs username validation? (That it's of a certain length, has only letters and numbers)
I'm trying to validate a username field in my form via client-side valdiation and I'm having some trouble.
I'm trying to use match them against regexs, which seems to work for my password strength/match. However when I try and change the regular expression to one that is suitable for usernames it doesn't work.
This is the regular expression that works, it checks to see if the length is at least 6 chars long.
var okRegex = new RegExp("(?=.{6,}).*", "g");
This is the other regular expression which does not work:
var okRegex = new RegExp("/^[a-z0-9_-]{3,16}$/");
How do I write a regex that performs username validation? (That it's of a certain length, has only letters and numbers)
Share Improve this question edited Jan 17, 2014 at 15:02 George Stocker 57.9k29 gold badges181 silver badges238 bronze badges asked Jan 17, 2014 at 14:54 user3112518user3112518 372 silver badges6 bronze badges 3- 1 What are the rules for usernames that you are trying to enforce? – rusmus Commented Jan 17, 2014 at 14:57
- good helping tool for regexps: regex101./r/bB5aL3 – caramba Commented Jan 17, 2014 at 15:04
-
if(/^[a-z0-9_-]{3,16}$/.test(userNameVar)) {//username is good!}
– Obversity Commented Jan 17, 2014 at 15:05
2 Answers
Reset to default 7You're mixing regex literals with the RegExp
constructor. Use one or the other, but not both:
okRegex = new RegExp('^[a-z0-9_-]{3,16}$');
or
okRegex = /^[a-z0-9_-]{3,16}$/;
As @zzzzBow answered you are mixing up two ways of using regular expressions. Choose one or the other. Now, a break down:
^
Matches the beginning of the string (that means that the string must start with whatever follows).
[a-z0-9_-]
Matches the charecters a-z, A-Z, digits 0-9 _ (underscore) and - (dash/hyphen).
{3,16}
States that there must be 3-16 occurences from the above character class.
$
Matches the end of the string, so the can't be anything after the 16 characters above.
Hope that helps.