How to do file validation in web2py and write custom validator to validate files?

In this article, I will explain built in validator IS_IMAGE  and  IS_UPLOAD_FILENAME, also a custom validator.
It is important to validate file uploaded on server to restrict malicious files like .py .php, .exe bat etc.
Web2py provides 2 validators to validate files, IS_IMAGE  and IS_UPLOAD_FILENAME .


It checks whether uploaded file is of type image and file is in any of supported image formats

Following statement Checks if uploaded file is either png or bmp


It checks whether uploaded file meets the given rules for filename and extension.

You can provide regular expressions in filename and extension parameters.
If filename or extension doesn’t match the expression/criteria then it shows error in form.
You can provide your own error message using argument error_message


If you want to allow all files starting with word ‘log’ and having extension “txt”:

Like IS_IMAGE validator we can not pass list of valid extensions to IS_UPLOAD_FILENAME validator.
But we can achieve this using regular expression or by writing our own validator

  1. Using regular expression:

The above expression will allow all the files having extension pdf, docx, doc or xls.

^ Matches the start of string

$ Matches end of the string

(pdf|docx|doc|xls) match any value from group pdf, docx, doc and xls

Read more about Regular Expression

2. Using custom validator:

Following validator checks whether uploaded file has extension from the valid extension list provided through argument extensions. It will also show error for empty file.


Advantage of custom validator is you can add and modify restriction as per your need

If you are facing any issues regarding above post please comment below