jQuery: validate file types

by maleol

HTML

<form action="#" method="post" enctype="multipart/form-data">
    <div>
         <input type="file" name="image" id="image" />
    </div>
</form>

CSS

label {
    display: block;
    font-weight: bold;
    margin-bottom: 0.5em;
}

JavaScript

(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);

$(function() {
    $('#image').checkFileType({
        allowedExtensions: ['jpg', 'jpeg', 'png'],
        error: function() {
            print('Insira apenas arquivos de imagens!'); 
            
        }
    });

});