views:

20

answers:

2

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 -?

A: 

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

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

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/
Amarghosh