Problem with validates_length_of

I’m passing a field called :year, to the game model for a new game. It
has
the validation

validates_length_of :year, :is => 4, :if => :check_year?

The if works (a similar validates_numericality_of :year) is being
checked,
so something before it is not working right. Why?

10 <- passed but shouldn’t
100 <- passes but shoulnd’t
1000 <- passes and it should
10000 <- passes but shouldn’t

Has anyone got any ideas why this might be happening, or how to fix?

Using Rails 2.1.0.

Thanks for your help.

Regards
Kieran

Its passed from a text field on a form, so technically it would be a
string,
but I guess it converts it on save because when I tried to concat with
another string, it wouldn’t change types.

And I’d really rather not change it to a string and back to int just for
one
validation (and even if I did, I’m not sure how at this point
(before_save
?)

Any other ideas?

Regards
Kieran

On Wed, Jun 4, 2008 at 1:03 AM, Thorsten M. <

what type does the field have?

validates_length_of would work only on string or text I guess, so if
it’s an integer it won’t work

On Jun 3, 2008, at 2:07 PM, Kieran P wrote:

Its passed from a text field on a form, so technically it would be
a string, but I guess it converts it on save because when I tried
to concat with another string, it wouldn’t change types.

And I’d really rather not change it to a string and back to int
just for one validation (and even if I did, I’m not sure how at
this point (before_save ?)

Any other ideas?

this should work?

validates_length_of :year.to_s, :is => 4

Or use validates_format_of with a regex that looks for 4 numerals. \d
{4}

– gw

Sorry Greg. Neither of those (:year.to_s or format_of) appear to work
for
some unknown reason.

Its very weird :frowning:

Regards
Kieran

Kieran P wrote:

1000 ← passes and it should
10000 ← passes but shouldn’t

Has anyone got any ideas why this might be happening, or how to fix?

Using Rails 2.1.0. http://2.1.0.

validates_numericality_of :year, :greater_than => 999, :less_than =>
10000

Lionel

Thanks Lionel. That worked :smiley: Finally my tests are passing :smiley:

Is the fact that length wouldn’t work on integers a bug in rails?

Regards
Kieran

On Wed, Jun 4, 2008 at 6:41 PM, Frederick C.
[email protected]

Is the fact that length wouldn’t work on integers a bug in rails?

no, numbers have no length as such (I wouldn’t know of any programming
language, library or whatever where they have)
The actual length would at least depend on the used number system
(decimal, hex…)

On 4 Jun 2008, at 00:59, Kieran P wrote:

Sorry Greg. Neither of those (:year.to_s or format_of) appear to
work for some unknown reason.

Lionel gave the answer, but it’s worth pointing out that
the :year.to_s thing couldn’t possibly work, since it’s just the same
as typing

validates_length_of ‘year’, :is => 4
which we know doesn’t work.

Fred