# Why is ruby ignoring allow\_nil?

**URL:** <https://www.ruby-forum.com/t/why-is-ruby-ignoring-allow-nil/127828>\
**Category:** Ruby\
**Created:** [February 1, 2008, 5:30pm UTC](https://www.ruby-forum.com/t/why-is-ruby-ignoring-allow-nil/127828 "2008-02-01T17:30:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![laredotornado](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/9dc877/32.png) [@laredotornado](https://www.ruby-forum.com/u/laredotornado)\
**Post date:** [February 1, 2008, 5:30pm UTC](https://www.ruby-forum.com/t/why-is-ruby-ignoring-allow-nil/127828/1 "2008-02-01T17:30:47Z")

</div>

Hi,

In my user model, I’m want to validate a field only if the field is  
not empty. So I’m trying

validates\_format\_of :work\_phone, :with =\> %r{^(+\d)_\s_((\d{3})\s\*)\*  
\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$}, :allow\_nil =\> true

but if my field, work\_phone, is empty, I get the error that the format  
is not valid. What is wrong with the above? - Dave

---

<div class="post-metadata">

**Author:** ![laredotornado](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/9dc877/32.png) [@laredotornado](https://www.ruby-forum.com/u/laredotornado)\
**Post date:** [February 1, 2008, 5:57pm UTC](https://www.ruby-forum.com/t/why-is-ruby-ignoring-allow-nil/127828/2 "2008-02-01T17:57:25Z")

</div>

On Feb 1, 2008 5:29 PM, laredotornado [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Hi,
> 
> In my user model, I’m want to validate a field only if the field is  
> not empty. So I’m trying
> 
> validates\_format\_of :work\_phone, :with =\> %r{^(+\d)_\s_((\d{3})\s\*)\*  
> \d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$}, :allow\_nil =\> true
> 
> but if my field, work\_phone, is empty, I get the error that the format  
> is not valid. What is wrong with the above?

That’s a Rails, not Ruby issue. While you may have some luck here,  
you’re more likely to have luck on the Rails mailing lists (see  
[http://lists.rubyonrails.org/mailman/listinfo/rails](http://lists.rubyonrails.org/mailman/listinfo/rails)).

Attempting to help you, I might _guess_ that the problem is that you  
have an empty field (field = “”), not a nil field (field == nil), but  
that is a guess - I don’t know Rails and how it handles these things.

Eivind.
