user386660
user386660

Reputation: 501

Regular expression + Ruby On Rails

I would like to validate my users, so they can only use a-z and - in their username.

validates_format_of :username, :with => /[a-z]/

However this rule also allows _ - and capital letters. How do I only allow letters, numbers, _ and -?

Upvotes: 1

Views: 767

Answers (2)

Amarghosh
Amarghosh

Reputation: 59451

This regex makes sure that the first character is a lowercase letter and the rest are either lowercase letters, numbers, hyphens or underscores.

/\A[a-z][a-z0-9_-]+\Z/

If you don't care about the first character, you can use

/\A[a-z0-9_-]+\Z/

If you want to make sure the name is minimum 4 characters long:

/\A[a-z][a-z0-9_-]{3,}\Z/

If you want to make sure the length is between 4 and 8

/\A[a-z][a-z0-9_-]{3,7}\Z/

If the length should be 6

/\A[a-z][a-z0-9_-]{5}\Z/

Upvotes: 3

bjg
bjg

Reputation: 7477

Your regular expression is not specific enough. You're looking for something like:

:with => /\A[a-z_]+\Z/

Upvotes: 0

Related Questions