The simplest way to validate file input type
Joanna Otmianowska
Posted on April 21, 2021
I've been working on a form lately and one day I got a task to add type validation to field input. My first thought was to simply check the file type after the file is being uploaded and, based on that, store this file in the list in my app or drop it. The idea was to have extensions whitelist and allow user to add only files that are on that whitelist to make sure that there is nothing insecure being introduced to our system.
I wanted to make sure that I covered all needed extensions so I ended up checking what were possible types supported by input field. And then I found it - accept
attribute in file input itself. Thanks to that user experience is just great - files not listed in the accept
attribute are simply greyed out so user can't select them. It allows to avoid confusion, dedicated error message and clearly shows the user what he or she can and cannot add to the form.
I recommend you to check the details in the docs, I just want to emphasise that this attribute can accept both file extensions and unique file type specifier. See examples below (taken from here)
-
accept="image/png"
oraccept=".png"
— Accepts PNG files. -
accept="image/png, image/jpeg"
oraccept=".png, .jpg, .jpeg"
— Accept PNG or JPEG files. -
accept="image/*"
— Accept any file with animage/*
MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.) -
accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
— accept anything that smells like an MS Word document.
Using accept
attribute instead of checking every file manually and then adding it to the list speeded my work. I didn't have to throw an error every time wrong file is added and explain to the user what he or she should do now. However, I wanted to be 1000% sure that there is no way to attach wrong file in the form. That's true that accept
attribute doesn't allow user to select file with type I didn't specify but you know... the form can be always compromised with external script. This is why I decided to add one more step before adding files to the list and wrote the function checking if selected file type is included in the extensions whitelist I have in the app. If it is not there - nothing happens (no error for the user is needed as this is edge case only if someone compromises the form). And the app is safe.
Posted on April 21, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.