validate or empty?

for instance, an image field for a house for sale, if the user leaves the image field empty, that means s/he has no picture, that could be fine. but, when s/he chooses submitting a pic, the pic file name must has either .jpg, gif, or PNG ext. I am using: validates_format_of :image, :with=>/^.*(.jpg|.JPG|.gif|.GIF|.png|.PNG)$/

You could try:

validates_format_of :image, :with=>/^($|.*(.jpg|.JPG|.gif|.GIF|.png|.PNG)$)/

That looks for the beginning of the string, then either the immediate end of the string, or some text ending in .jpg etc

As a side note, you might actually want this:

validates_format_of :image, :with=>/^($|.*(.jpe?g|.gif|.png)$)/i

For case-insensitive matching, in case they have foo.Jpg, and some programs use .jpeg instead of .jpg, which this regex handles as well.

Hi, Im using image_science package for uploading images images in my application.

Can anybody tell me how to validate the format of images before uploading images ?

This is my view

<TD HEIGHT=24>Upload Image </TD>               <TD HEIGHT=24 ><%= file_field 'image','uploaded_data' %></TD>       </TR>

and class is defined as this

class Image < ActiveRecord::Base

  has_attachment :content_type => :image,                  :storage => :file_system,                  :size => 0.megabyte..2.megabytes,                  :resize_to => '320x200>',                  :thumbnails => { :thumb => '50x50>' },                  :processor => 'ImageScience'   validates_as_attachment end

-Saurav

When you say “validate the format”, what exactly are you trying to validate? The size (width and height)? The image quality (72px/in)?

The browser won’t give you much information prior to actually uploading the files, so the answer is most likely no.

Not sure if I’ve helped much, but good luck with it.

Im trying to validate the format of image types, I want to upload image of either jpg of png types only. Is there any way around to do it ?

Well, if you want to validate the file name only, sure. Ultimately the file can be anything that the user names it, but here is how it’s done in the depot app from the rails book:

validates_format_of :image_url,
                    :with     => %r{\.(gif|jpg|png)$}i,
                    :message  => "must be a URL for a GIF, JPG, or PNG image"

Is that what you are looking for?

Hi Saurav, The :content_type => :image option on your has_attachment line will limit it to "all standard image types" (which I think consists of .gif, .png and .jpg). You can override this by passing it an explicit list of MIME types:

has_attachment :content_type => ['image/png', 'image/jpeg']

- Matt