views:

681

answers:

4

Hello,

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 spaces ._@

Username should use only letters, numbers, spaces, and .-_@ please.

Any ideas?

Best regards. Asbjørn Morell

+2  A: 

The [] may contain several "rules" so [a-z0-9] gives lowercase letters and numbers

the special character - must go at the start of the rule

Does

[-a-z0-9@_.]

give the effect you want?

djna
[-A-Za-z0-9@_.] <-- with uppercase, just in case.
beggs
he only asked for a-z ;-)
djna
I would rather mark it as case insensitive.
Svish
Hmmm no sorry, it gives me Username should use only letters, numbers, spaces, and .-_@ please.
atmorell
+6  A: 

You may need to say the whole string must match:

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

You may also need to replace ^ with \A and $ with \Z, if you don't want to match a newline at the start/end. (thanks to BaroqueBobcat)

Appending an i will cause it to match in a case-insensitive manner. (thanks to Omar Qureshi).

(I also originally left off the +: thanks to Chuck)

Matthew Schinckel
agreed but as /^[-a-z]$/i for case insensitivity
Omar Qureshi
You example always returns invalid :/
atmorell
test it in irb .. re = /^[-a-z]$/i; "foo" =~ re
Omar Qureshi
It needs to be `/^[-a-z]+$/` (with an `i` after the second slash if you want it case-insensitive). Without a +, you're saying it has to be exactly one character long.
Chuck
^ and $ match the beginnings and ends of lines. To ensure no newlines use \A \Z which match the beginning and end of the string.
BaroqueBobcat
A: 

Simply change the regular expression to match all characters your specification states (\w covers all alphanumeric characters -- letters and numbers -- and an underscore).

validates_format_of :username, :with => /[\w \.\-@]+/
Damir Zekić
Your example is pretty close however the user can still use . and spaces. my.......new user
atmorell
There is no limit here to prevent longer strings matching. This will match any string that contains at least one of the matched characters.
Matthew Schinckel
A: 
validates_format_of :username, :with => /^[\w\-@]*$/

Note the *, which means '0 or more'

Mr. Matt
Same problem... spaces and . is still allowed :/
atmorell