I am BARRY HESS > Blog

Detect Alphanumeric in Ruby via Regular Expressions

I do not understand regular expressions. It’s on my list to get to know them better and make some use of them to gain understanding, but I have not done it yet. It’s a deficiency that I am aware of.

All I wished to do was verify that a user-keyed login and password were fully alphanumeric (including ‘‘). I found one reference out on the InterWeb, though there was a bug in that code. I went with the following validation code in my Rails model class:

validates_format_of :login, :password, :display_name,
                    :with => /^\w+$/i,
                    :message => "can only contain letters and numbers."

Wow, do I look like an idiot posting this - what a breakthrough I must say! But understand there will be other idiots like me digging for the same solution. Hopefully those idiots will run into this post and be on their merry way.

TextMate actually has a nice regular expression manual online that aligns pretty well with Ruby’s implementation. I enjoyed looking at that a lot more than the Pragmatic Ruby Programming book.