# Conditional validates\_inclusion\_of execution problem

**URL:** <https://www.ruby-forum.com/t/conditional-validates-inclusion-of-execution-problem/82200>\
**Category:** Rails\
**Created:** [January 18, 2007, 1:27am UTC](https://www.ruby-forum.com/t/conditional-validates-inclusion-of-execution-problem/82200 "2007-01-18T01:27:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [January 18, 2007, 1:27am UTC](https://www.ruby-forum.com/t/conditional-validates-inclusion-of-execution-problem/82200/1 "2007-01-18T01:27:28Z")

</div>

All,

I have a field that I’m validating with validates\_numericality\_of on as  
well as validates\_inclusion\_of, like so:

validates\_numericality\_of :number\_of\_owners,  
:only\_integer =\> true,  
:message =\> ‘must be a whole number’

validates\_inclusion\_of :number\_of\_owners,  
:in =\> 1…3,  
:message =\> ‘should be between 1 and 3’,  
:if =\> Proc.new {|x| x.number\_of\_owners =~ /\d+/}

As you can see, I’m using the :if clause to limit the inclusion  
validation to cases where the field actually contains digits.

But the inclusion valiation never runs. Is this because  
x.number\_of\_owners isn’t set yet at the time the :if is evaluated? How  
can I defer the inclusion validation until I know that the numericality  
has been satisfied?

Thanks,  
Wes

---

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [January 18, 2007, 1:35am UTC](https://www.ruby-forum.com/t/conditional-validates-inclusion-of-execution-problem/82200/2 "2007-01-18T01:35:07Z")

</div>

On 1/18/07, Wes G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> can I defer the inclusion validation until I know that the numericality  
> has been satisfied?

Wes, I think the problem is that your trying a regexp on an Integer.  
Instead you could use

:if =\> Proc.new{ |x| x.number\_of\_owners.is\_a?(Integer) }

You might consider allowing nil for this as well.

Hope that helps

---

<div class="post-metadata">

**Author:** ![weyus](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/7ab992/32.png) [@weyus](https://www.ruby-forum.com/u/weyus)\
**Post date:** [January 18, 2007, 1:41am UTC](https://www.ruby-forum.com/t/conditional-validates-inclusion-of-execution-problem/82200/3 "2007-01-18T01:41:51Z")

</div>

This seems to work - the attribute is an integer, not a string.

validates\_inclusion\_of :number\_of\_owners,  
:in =\> 1…3,  
:message =\> ‘should be between 1 and 3’,  
:if =\> Proc.new {|aqi| aqi.number\_of\_owners.to\_s  
=~ /\d+/}
