Kieran1
(Kieran)
June 3, 2008, 12:54pm
1
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.
Kieran1
(Kieran)
June 3, 2008, 9:07pm
2
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
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
Kieran1
(Kieran)
June 3, 2008, 11:59pm
4
Sorry Greg. Neither of those (:year.to_s or format_of) appear to work for some unknown reason.
Its very weird
Regards
Kieran
Kieran P wrote:
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. <http://2.1.0 .>
validates_numericality_of :year, :greater_than => 999, :less_than => 10000
Lionel
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
Kieran1
(Kieran)
June 4, 2008, 9:12am
7
Thanks Lionel. That worked Finally my tests are passing
Is the fact that length wouldn’t work on integers a bug in rails?
Regards
Kieran
11175
(-- --)
June 4, 2008, 9:44am
8
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...)