Tuesday, April 28, 2015

Simple File Upload Validation Using jQuery

If you are creating a form with file upload option then you might be needed files with some specific extensions. For example, you are creating a form for applying job. So you have to add a file upload option to allow uploading resumes of the candidates. Then you need only files types like doc,pdf etc.Files like mp3, avi, exe etc.are not required.

If haven’t added a proper validation then users can upload any types of files. Even attackers can upload some scripts to hack your site. To avoid all these craps we need a proper validation. Here I will show you how to add file upload validation using jquery.

This a simple regex based javascript that can help you out with the solution. It’s based on the file extension of file being browsed and clears the input field if validation fails. Here I have used some file extensions that you can change according to your needs and requirements.

Note : This a client side validation only. The best practice is to add server side validations also.

Before implementing the actual code we need to load jquery library. Here I use latest live jquery api. So we need to add below code first. Usually we are including this line inside the <head> tag.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Now jquery can work. So we have to add below code after this code.

<script>
$(document).ready(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(jpg|jpeg|txt|png|docx|gif|doc|pdf|xml|bmp|ppt|xls)$");

if(!(regex.test(val))) {
$(this).val('');
alert('Unsupported file');
} }); });
</script>

jpg|jpeg|txt|png|docx|gif|doc|pdf|xml|bmp|ppt|xls

All done. !! When ever you are trying to select a file to upload, if the file is not among one of the above extension it will show error alert message “Unsupported file”.


Enjoy. !! If you have enjoyed please add your feedback in comments. Special thanks to Joel James.