# Why is "valid\_numericality\_of" executed when value is empty?

**URL:** <https://www.ruby-forum.com/t/why-is-valid-numericality-of-executed-when-value-is-empty/145670>\
**Category:** Rails\
**Created:** [August 12, 2008, 7:06pm UTC](https://www.ruby-forum.com/t/why-is-valid-numericality-of-executed-when-value-is-empty/145670 "2008-08-12T19:06:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [August 12, 2008, 7:06pm UTC](https://www.ruby-forum.com/t/why-is-valid-numericality-of-executed-when-value-is-empty/145670/1 "2008-08-12T19:06:55Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![josh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/45deac/32.png) [@josh](https://www.ruby-forum.com/u/josh)\
**Post date:** [August 12, 2008, 9:04pm UTC](https://www.ruby-forum.com/t/why-is-valid-numericality-of-executed-when-value-is-empty/145670/2 "2008-08-12T21:04:49Z")

</div>

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?
