Validations for File Upload with Rails

File uploading with Rails is a topic that’s really hot for my readers. Mike asked the other day, how he could do validations for uploaded files.

There are certainly many ways and it really depends on your specific setup and what you would like to validate. So this can only be a small hint in a right direction:

Modify the controller’s response

When we try to create the file, the controller renders create.js.erb. The file could look like this before we validate.

<% if @upload.new_record? %>
  console.log('ERROR');
<% else %>
  if ($('h1') !== undefined) {
    $('h1').append("<%=j render partial: 'uploads/upload', locals: { upload: @upload } %>");
  }
<% end %>

If an Upload is invalid, the model will have error messages set. You can retrieve them by calling @upload.errors.full_messages. We just have to write them to the screen.

<% if @upload.new_record? %>
  <% if @upload.errors.any? %>
      $('form').prepend("<%=j render partial: 'shared/error_messages', locals: { error_messages: @upload.errors.full_messages } %>");
  <% end %>
<% else %>
  if ($('h1') !== undefined) {
    $('h1').append("<%=j render partial: 'uploads/upload', locals: { upload: @upload } %>");
  }
<% end %>

Perhaps we need to do this more often than for this one form. That’s why I use a shared partial _error_messages.js.erb. It looks like this.

<div id="error_explanation">
  <div class="alert alert-danger">
    The form contains <%= pluralize(error_messages.count, "error") %>.
  </div>
  <ul>
    <% error_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
  </ul>
</div>

So now, when you try to upload an invalid file, you will get your errors printed to the screen.

Thank you for reading.