How do I display validation errors for a FileField?

<%- if @topic_view.topic.tags.present? %>
<%= t 'js.tagging.tags' %>: <%- @topic_view.topic.tags.each do |t| %> <%= t %> <%- end %>
<% end %>

I have a simple frontend form on Silverstripe 4. One of the fields is a FileField for uploading a single file.

I’ve successfully added validation to the FileField to set the allowed file size and extensions:

$fileField = FileField::create('Photo');
$fileField->getValidator()->setAllowedMaxFileSize("10M");
$fileField->getValidator()->setAllowedExtensions(['jpg','png']);

This works, but the validation messages are not making it through to the form, so if a user submits an image that it too large, it just seems to discard the file and says:

“Photo” is required

rather than:

Filesize is too large…

I can see that these messages are set in Upload_Validator, and for FileField it says:

Please set a validator on the form-object to get feedback about imposed filesize/extension restrictions.

However, even after reading the validation docs, I’m not sure how to do this. Is someone able to clarify exactly what is required here? Thanks!

Not the answer to your specific question, but I’d advocate adding some client-side validation to the form in the first instance. A bit of simple Javascript can get the file size without having to wait for the upload (saving everyone some time and bandwidth).

It obviously shouldn’t be the only validation you use, but it’ll probably catch the majority of over-size files for normal users.

Something like the following (one of the first Stackoverflow examples I came across):

<!-- You can set the onchange attribute directly, or bind it with a listener on page load -->
 <input onchange="ValidateSize(this)" type="file">


function ValidateSize(file) {
        var FileSize = file.files[0].size / 1024 / 1024; // in MiB
        if (FileSize > 2) {
            alert('File size exceeds 2 MiB');
        } else {
            // Some other action
        }
    }
1 Like