Problem with validates_length_of an integer

What is your question?

The validation you show should be correct. It should do exactly what
you want. If the field is left empty allow_nil => true should skip
validation of length.

It seems as though you can only use validates_length_of with strings.
So you can either do what a previous poster mentioned, and use the
following:

# this will ensure that the position value is between 1 and 3 characters
validates_length_of :position, :within => 1..999

or you can do something like this:

def validate
  errors.add(:position, "should be between 1 and 3 characters in
length") if position.to_s.length < 1 or position.to_s.length > 3
end

Adam

It seems as though you can only use validates_length_of with strings.
So you can either do what a previous poster mentioned, and use the
following:

# this will ensure that the position value is between 1 and 3 characters
validates_length_of :position, :within => 1..999

What about negative values? -22 is 3 chars, but would fail on the above..
? I admit I don't know what hte original problem was... :slight_smile:

yeah good point, it was also supposed to be validates_inclusion_of
instead of validates_length_of. You could use :within => -999..999 if
you wanted then, or use the manual validation with to_s (and take into
account any leading negative signs).

Adam

if the telephone column definition in your database is set to default
to null, you shouldn't need the :if => Proc.new ... line. That's what
:allow_nil => true is for. It doesn't execute the validation if the
field was empty.

Adam

I should clarify: using :allow_nil => true won't work with a string
attribute, only with an integer type attribute. So using :allow_nil
=> true would've worked for your initial question where you were
trying to validate the length of an integer (position column),
however, the problem in that instance was that validates_length_of
cannot be used with an integer. And as for the problem with the
telephone number validation, since that's a string, you can't use
:allow_nil => true with it.

So looks like you're back to your solution of using the :if condition
with string type attributes, at least until that patch is committed..

Adam