user3112518
user3112518

Reputation: 37

regex that checks that a string is between two lengths and 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)

Upvotes: 2

Views: 5833

Answers (2)

rusmus
rusmus

Reputation: 1665

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.

Upvotes: 2

zzzzBov
zzzzBov

Reputation: 179056

You'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}$/;

Upvotes: 7

Related Questions