-
Notifications
You must be signed in to change notification settings - Fork 403
Paperclip
Eliot Sykes edited this page Oct 3, 2017
·
12 revisions
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
Lets assume you have:
validates_attachment :photo,
content_type: {content_type: [/\Aimage\/.*\z/, 'application/pdf' ] }, # "image/jpeg", "image/gif" e.t.c.
size: { less_than: 2.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:
// For supported browsers see http://caniuse.com/#search=file%20api
var browserSupportsFileApi = !!(window.File && window.FileList && window.FileReader);
if (browserSupportsFileApi) {
window.ClientSideValidations.validators.local['attachment_size'] = function(element, options) {
if(browserSupportsFileApi && element[0].files &&
element[0].files[0] &&
element[0].files[0].size >= options.less_than) {
// If you defined a custom message you may need to
// return `options.messages.numericality` instead
return options.messages.less_than
}
}
window.ClientSideValidations.validators.local['attachment_content_type'] = function(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;
}
}
}