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.
accept=".png"— Accepts PNG files.
accept=".png, .jpg, .jpeg"— Accept PNG or JPEG files.
accept="image/*"— Accept any file with an
image/*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.
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.