Why is "valid_numericality_of" executed when value is empty?

Hi all

I’m wondering why

validates_numericality_of :xxx

is executed also when xxx is left empty? Shouldn’t it just be disabled
in this case?

validates_numericality_of :xxx,
:if => Proc.new { |obj| obj.xxx }

…looks a bit awkward to me.

And when I use

validates_presence_of :xxx
validates_numericality_of :xxx

…it’s very unpractical to have two error messages displayed when empty
("…can’t be blank" and “…is not a number”).

What do you think?

Have you tried this option?:

:allow_nil - Skip validation if attribute is nil (default is false).
Notice that for fixnum and float columns empty strings are converted to
nil.

validates_presence_of :xxx
validates_numericality_of :xxx

…it’s very unpractical to have two error messages displayed when empty
("…can’t be blank" and “…is not a number”).
validates_numericality_of can be interpreted a couple different ways.
The way I read it the value must be a number. Empty string or nil is not
a number therefore invalid.

So I would say that putting validates_presence_of and
validates_numericality_of is redundant. If you want an column to be
optional but if specified must be a number then you should use:

validates_numericality_of :xxx, :allow_nil => true

Joshua M. wrote:

Hi all

I’m wondering why

validates_numericality_of :xxx

is executed also when xxx is left empty? Shouldn’t it just be disabled
in this case?

validates_numericality_of :xxx,
:if => Proc.new { |obj| obj.xxx }

…looks a bit awkward to me.

And when I use

validates_presence_of :xxx
validates_numericality_of :xxx

…it’s very unpractical to have two error messages displayed when empty
("…can’t be blank" and “…is not a number”).

What do you think?