I need some help with a regular expression for a validates_format_of
statement in my model. I have a user login field and i only want to
allow the login field to have alphanumeric characters and the underscore
( a-z, A-Z, 1-9, _ ) those are the only characters I want to allow.
What is the properly Ruby RegExp to do this that I would use in the
:with => // statement of the validates_format_of
The \w character class is all alphanumerics plus underscore -- and the
\W character class is the opposite. Assuming you really don't want to
allow zero, you could do:
:with => /[^\W0]+/
i.e., no character (that's the ^) that is either \W or 0.
Note, however, that there's been some flux in the question of whether
or not your regex gets automatically wrapped by beginning and
end-of-string anchors. That regex assumes that the anchors are added
(though I hope in the long run they aren't). Try some tests, and if
you need to, you can wrap it in anchors like this: