Skip to content
Aleksey edited this page Dec 6, 2016 · 12 revisions

Paperclip

If you want to validate the presence of the file on your form you'll need to add a presence validator for the attribute being used by Paperclip

has_attachment :file
validates_presence_of :file

Size and content validation

Lets assume you have:

validates_attachment :photo,
                     content_type: {content_type: [/\Aimage\/.*\z/, 'application/pdf' ] }, # "image/jpeg", "image/gif" e.t.c.
                     size: { in: 0..10.megabytes }

Than you'll have validators with names attachment_size and attachment_content_type, they have very simple structure which you can observe in browser debugger. Since you know the structure than you can implement validation like this:

  function attachment_size_validation(element, options) {
      if(element[0].files && element[0].files[0] && element[0].files[0].size >= options.less_than_or_equal_to) {
        return options.messages.less_than_or_equal_to
      }
  }
  function attachment_content_type_validation(element, options) {
    if(element[0].files && element[0].files[0]) {
      for (var i in options.content_type) {
          var rule = options.content_type[i]
          var re = new RegExp(rule.source || rule, rule.options);
          if( re.test(element[0].files[0].type) ) {
              return false;
          }
      }
      return options.message;
    }
  }
  document.addEventListener("turbolinks:load", function () {
      window.ClientSideValidations.validators.local.attachment_size = attachment_size_validation;
      window.ClientSideValidations.validators.local.attachment_content_type = attachment_content_type_validation; } )

Clone this wiki locally