9

I've found that Paperclip can validate file content type, i.e. image/jpeg, but I want to specifically validate the extension. This is because I'm working with an obscure extension that won't get a consistent content type. Anyone know if this is doable, or a good way to do this?

Geoff
  • 9,470
  • 13
  • 52
  • 67

1 Answers1

16

Guess, there is no need to validate it with paperclip's method. You can rather use something like:

has_attached_file :attachment
validates_format_of :attachment_file_name, :with => %r{\.(docx|doc|pdf)$}i

Edit:

Alternatively, to validate it with paperclip:

validates_attachment_content_type :attachment, :content_type => 'text/plain'

^ it will generate content-type mismatch errors automatically.

  • 3
    Thanks, this worked. Simple follow-up: how can you customize the error message? This doesn't seem to work: validates_format_of :attachment_file_name, :with => %r{\.(txt)$}i, :message => "Can only upload .txt files." – Geoff Jul 02 '11 at 06:47
  • That's weird! but anyway check the edit for alternate solution. –  Jul 02 '11 at 15:16
  • The second alternative here will probably also accept files with other file endings that have MIME type "text/plain". A number of such file endings can be found e.g. at [http://reference.sitepoint.com/html/mime-types-full](http://reference.sitepoint.com/html/mime-types-full). – lossius Sep 22 '13 at 12:45
  • 1
    That can be spoofed. Make sure to validate it a legitimate way besides matching the file name as well. – JackHasaKeyboard Sep 22 '16 at 17:36