validates_file_format_of only when is there an image

Luca Roma wrote:

i have a model with this:
file_column :image
validates_file_format_of :image, :in => ["gif", "png", "jpg"]

If inthe form the user not insert the image i receive an error.
If i remove:
validates_file_format_of :image, :in => ["gif", "png", "jpg"]
it works.

Is possible do the validation only when user insert the image in form?

i try with:
validates_file_format_of :image, :in => ["gif", "png", "jpg"],:if
=>:image?
but it not works.

The option

   :allow_nil => true

should do the trick.

Didn't seem to work for me.

chovy wrote:

Didn't seem to work for me.

Luca Roma wrote:

Is possible do the validation only when user insert the image in form?
i try with:
validates_file_format_of :image, :in => ["gif", "png", "jpg"],:if
=>:image?
but it not works.

The option

   :allow_nil => true

should do the trick.

That's unexpected. The image attribute should be nil if nothing
has been uploaded, and the validation should be skipped because
the :allow_nil is passed into the validates_each that's used by
validates_file_format_of.

You could try :allow_blank => true instead. But what's been
working for me is a modified file_column that puts an
"unless value.blank?" inside the validates_each. I think I did
this before validates_each supported the allow_blank option.

So perhaps rather than :allow_nil, :allow_blank is needed,
although I'm not sure why because the no-image condition is
a nil attribute, not an empty string.

I'm actually using this with validates_format_of (neither allow_blank
or allow_nil work).