# Conditional validation?

**URL:** <https://www.ruby-forum.com/t/conditional-validation/133356>\
**Category:** Rails\
**Created:** [March 30, 2008, 9:08pm UTC](https://www.ruby-forum.com/t/conditional-validation/133356 "2008-03-30T21:08:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![drsharp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e9bcb4/32.png) [@drsharp](https://www.ruby-forum.com/u/drsharp)\
**Post date:** [March 30, 2008, 9:08pm UTC](https://www.ruby-forum.com/t/conditional-validation/133356/1 "2008-03-30T21:08:58Z")

</div>

Hi, I have followed the tutorial in the AWDWR book for uploading an  
image. This involves adding the following field to the form.  
\<%= f.file\_field :uploaded\_picture %\>

The model then goes to work on the data to store it in the database,  
with the following:

validates\_format\_of :content\_type,  
:with =\> /^image/,  
:message =\> “-- you can only upload pictures”

def uploaded\_picture=(picture\_field)  
self.name = base\_part\_of(picture\_field.original\_filename)  
self.content\_type = picture\_field.content\_type.chomp  
self.data = picture\_field.read  
end

def base\_part\_of(file\_name)  
File.basename(file\_name).gsub(/[^\w.\_-]/, ‘’ )  
end

Now, all of this works fine, but I would like the picture upload to be  
an optional feature, but if the user fills in the form and leaves the  
field blank, the following error is displayed

undefined method `original\_filename’ for “”:String

I’ve tried adding "unless picture\_field.empty/nil? to the  
uploaded\_picture action, but I can’t get anything that works for both an  
image being supplied and no image being supplied.  
Can anyone suggest a way to get around this? Thanks.

---

<div class="post-metadata">

**Author:** ![drsharp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e9bcb4/32.png) [@drsharp](https://www.ruby-forum.com/u/drsharp)\
**Post date:** [March 30, 2008, 9:49pm UTC](https://www.ruby-forum.com/t/conditional-validation/133356/2 "2008-03-30T21:49:18Z")

</div>

Dan S. wrote:

> validates\_format\_of :content\_type,  
> :with =\> /^image/,  
> :message =\> “-- you can only upload pictures”
> 
> I’ve tried adding "unless picture\_field.empty/nil? to the

Try “unless picture\_field.blank?” and add “:allow\_blank =\> true” to the  
validation line.

If you are using Rails earlier than version 2, then make that  
“:allow\_nil =\> true”, though I’m not sure if that will be as successful.

---

<div class="post-metadata">

**Author:** ![drsharp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e9bcb4/32.png) [@drsharp](https://www.ruby-forum.com/u/drsharp)\
**Post date:** [March 30, 2008, 10:08pm UTC](https://www.ruby-forum.com/t/conditional-validation/133356/3 "2008-03-30T22:08:05Z")

</div>

Thanks, that seems to have worked:)
