views:

226

answers:

2

In my user model, I have an attribute called "nickname" and validates as such:

validates_format_of :nickname, :with => /[a-zA-Z0-9]$/, :allow_nil => true

However, it is currently letting this string pass as valid:

a?c

I only want to accept alphanumeric strings - does anyone know why my regular expression is failing? If anybody could suggest a better regular expression, I'm all ears.

+9  A: 

You need to anchor the pattern on both sides:

/^[a-zA-Z0-9]+$/
Robert Gamble
That's limited to one character.
Joel Coehoorn
Yep, just fixed that.
Robert Gamble
Yup, that change works in my code as well. Thanks!
Allan L.
Robert, I apologize for not marking your answer as the answer I accepted previously.I didn't realize all I had to do was click on the check mark.Again, my apologies.
Allan L.
+17  A: 

That will match true if the string ends with a valid character. No validation on anything in the middle. Try this:

^[a-zA-Z0-9]*$
Joel Coehoorn
You probably want a + not a *, as it is, it will match an empty string.
Dan
The "*" before the "$" fixed everything.I had the "^" in there previously, but I took it out because it helped passed some of my specs.thank you so much for responding so quickly!
Allan L.
I considered +, but part of the original question was "allow_nil: true", which indicated to me that an empty string should be okay.
Joel Coehoorn