Forum: Ruby on Rails validates_format_of

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Afroz (Guest)
on 2007-04-22 18:10
(Received via mailing list)
Hi everyone!
I'm new to rails and have been playing around a bit. Unfortunately, I
seem to be a bit stuck at the moment. Since I'm just playing around,
I'm using a dynamic scaffold. In my model file (which is tied to a
database table), I have the following line:
validates_format_of :grade, :with => /^[0-9]+$/, :message => 'should
be zero or a positive integer'

'grade' is an int(6) column in my table. What I would expect is that
if I enter some random letters such as "asdas" in a form, then the
string should be considered invalid and should throw an error.
However, this does not occur. Instead, the form saves the data into
the table with a value of 0.
During my tests, I changed [0-9] to [1-9]. On doing so, "asdas" would
not be accepted anymore, but "123as" would. "123" would be saved to
the database.
Perhaps my understanding of the above regular expression is wrong? It
is my first time using regexp. However, I wrote a little test program
in ruby:
tst = Array.new
tst[0] = 'letters'
tst[1] = '123let'
tst[2] = 'let123'
tst[3] = '1234'
tst[4] = '5'
tst[6] = '1.5'

tst.each do |type|
  puts "#{type}\n" if type =~ /^[0-9]+$/
end

As I expect, only 1234 and 5 are printed. It seems to work as expected
in this little program, but not during validation.
Any help/suggestions would be greatly appreciated!
Ben Munat (Guest)
on 2007-04-22 22:08
(Received via mailing list)
Yeah... I've seen something like this. I think rails is attempting to
convert the input to int and just makes it zero if it gets letters. I
know that sounds stupid, but I'm pretty sure that's what it does.

The good news is that you should be able to use
validates_numericality_of to check for letters. The problem with that is
that as near as I can tell, you can't specify a positive value (you can
specify only_integer though).

The trick that that validation uses -- and an excellent thing to learn
about rails -- is it checks the value "before_type_cast". ActiveRecord
keeps a buffer of the input values before they are type cast and you can
access them with <field_name>_before_type_cast.

So, you could try just changing :grade in your validates_format_of to
:grade_before_type_cast. Not sure if that will work at all, but it
should in theory.

Hope this helps....

b
This topic is locked and can not be replied to.