I am using CarrierWave, and I would like to validate file names and only allow file uploads if the extension is .gif
, .png
, .jpg
, .jpeg
, or if there is no file extension.
Sometimes users upload files with no extensions. For example:
http://t2.gstatic.com/images?q=tbn:ANd9GcTCD2TLvYI8a4ChgBaYK_JaRfedvXLr3HXQfj0arXXAii3o2yjf
I am aware of the possibility of uncommenting the following lines in uploaders/image_uploader.rb
, but I don't know of a way of additionally saying "allow any of these extensions only if there is a file extension".
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
#def extension_white_list
# %w(gif jpg jpeg png)
#end
As well, in my model I have a validation as follows, but for some reason bad-extension.bad
passes.
validates :image, allow_blank: true, format: {
with: %r{\.(gif|jpe?g|png)\z}i,
message: 'must be a GIF, JPG, or PNG'
}, if: :filename_has_extension?
def filename_has_extension?
image =~ /\./
end