jQuery: validating file types

jQuery: validating file types

How to validate file types with jQuery.

Validating file types is pretty easy with jQuery. The only thing we need to do is to extract the file extension from the input's value and bind a change event to that element in order to check user's choices.

Having the following form:


<form action="#" method="post" enctype="multipart/form-data">
    <div>
        <label for="image">Upload image (JPEG only)</label>
        <input type="file" name="image" id="image" />
    </div>
</form>

which accepts only JPEG files, we can define a general-purpose jQuery plugin:


(function($) {
    $.fn.checkFileType = function(options) {
        var defaults = {
            allowedExtensions: [],
            success: function() {},
            error: function() {}
        };
        options = $.extend(defaults, options);

        return this.each(function() {

            $(this).on('change', function() {
                var value = $(this).val(),
                    file = value.toLowerCase(),
                    extension = file.substring(file.lastIndexOf('.') + 1);

                if ($.inArray(extension, options.allowedExtensions) == -1) {
                    options.error();
                    $(this).focus();
                } else {
                    options.success();

                }

            });

        });
    };

})(jQuery);

The above plugin accepts three options:

  1. allowedExtensions – An array of strings which define the allowed extensions (e.g. ['jpg', 'jpeg'])
  2. success() – A callback function to be executed when the inserted file passes the validation
  3. error() – A callback function to be executed when the inserted file fails the validation.

An example:


$(function() {
    $('#image').checkFileType({
        allowedExtensions: ['jpg', 'jpeg'],
        success: function() {
            alert('Success');
        },
        error: function() {
            alert('Error');
        }
    });

});​

[view-example url="http://jsfiddle.net/gabrieleromanato/QWQdz/"]