Katie H
Katie H

Reputation: 2293

Username Regular Expression

I need the username to be two or more characters of a-z, 0-9, all downcase. This is the current regex I am using

USER_REGEX = /\A[a-z0-9][-a-z0-9]{1,19}\z/i

With this regex, users are able to use uppercase charters in their username. How do I modify the current regex to avoid that?

Upvotes: 0

Views: 100

Answers (2)

Jan Nielsen
Jan Nielsen

Reputation: 11799

The regular expression to filter for two to twenty lower-case characters or digits is

  /^[a-z0-9]{2,20}$/

which means:

  1. ^ at the front of input
  2. a-z accept lower-case 'a' through 'z'
  3. 0-9 accept '0' through '9'
  4. {2,20} accept 2 to 20 elements from preceding [] block
  5. $ until the end of input

You can make a regular expression case-insensitive with trailing i, as in your example; that appears to be the root of problem. That said, I don't know Ruby's peculiarities with respect to regular expressions.

Upvotes: 4

Taryn East
Taryn East

Reputation: 27747

If you must keep the RegEx - remove the "i" from the end

USER_REGEX = /\A[a-z0-9][-a-z0-9]{1,19}\z/i
USER_REGEX = /\A[a-z0-9][-a-z0-9]{1,19}\z/

the "i" tells the RegEx to be a case-insensitive RegEx.

but you want it to be case-sensitive and only match on lowercase letters.

Upvotes: 3

Related Questions