Validates_length_of with char field

I am new to ruby/rails and am having a problem with validates_length_of.
It seems to work fine on a varchar field, but when I try it on a char
field the extra characters are silently truncated and the message
appears that the record was successfully updated.

How can I get my app to produce my error message instead? I’ve tried
various variations, but here’s one of my tries:

validates_length_of :State, :minimum => 2, :maximum => 2,
:message => “Use the two-letter state abbreviation”

I know I can use a drop-down list instead (that’s my next exercise) but
I’d like to know how to do this for other char fields as well. Or is the
char issue a red herring and something else is wrong with my code?


don’t know if using :minimum and :maximum would cause any problems,
but you could just use:

validates_length_of :state, :is => 2, :message => “Use the two-letter
state abbreviation”

or even

validates_format_of :state, :with => /^[a-zA-Z]{2}$/

that way you know you are getting a 2 character field that only
contains A-Z and or a-z characters.


Thanks, Chris. They both worked!

My problem was that I was adding the validates_length_of :State line to
the wrong version of my app. But for other newbies - Rails still didn’t
like the :minimum, :maximum combo and replied “too many arguments”.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs