programer.tips, another cool thing from @nghuuphuoc!

file validator

Validate file

Validators

Improve it on Github

Options

Option HTML attribute Type Description
extension data-bv-file-extension String The allowed extensions, separated by a comma
maxSize data-bv-file-maxsize Number The maximum file size in bytes
minSize data-bv-file-minsize Number The minimum file size in bytes
message data-bv-file-message String The error message
type data-bv-file-type String

The allowed MIME type, separated by a comma.

For example: Setting image/jpeg,image/png,application/pdf only allows to upload JPEG, PNG image and PDF document.

See popular MIME types listed below.

The maxSize and type are only used if the browser supports HTML 5 File API.

When setting options via HTML attributes, remember to enable the validator by setting data-bv-file="true".

Popular MIME types

The following table shows popular MIME types. For other MIME type, you can refer to the complete list.

MIME type File extensions
application/msword doc
application/pdf pdf
application/rtf rtf
application/vnd.ms-excel xls
application/vnd.ms-powerpoint ppt
application/x-rar-compressed rar
application/x-shockwave-flash swf
application/zip zip
audio/midi mid midi kar
audio/mpeg mp3
audio/ogg ogg
audio/x-m4a m4a
audio/x-realaudio ra
image/gif gif
image/jpeg jpeg jpg
image/png png
image/tiff tif tiff
image/vnd.wap.wbmp wbmp
image/x-icon ico
image/x-jng jng
image/x-ms-bmp bmp
image/svg+xml svg svgz
image/webp webp
text/css css
text/html html htm shtml
text/plain txt
text/xml xml
video/3gpp 3gpp 3gp
video/mp4 mp4
video/mpeg mpeg mpg
video/quicktime mov
video/webm webm
video/x-flv flv
video/x-m4v m4v
video/x-ms-wmv wmv
video/x-msvideo avi

Example

The following form allows to upload JPEG, PNG image which is smaller than 2 MB in size.

<form id="fileForm" class="form-horizontal" enctype="multipart/form-data">
    <div class="form-group">
        <label class="col-sm-3 control-label">Avatar</label>
        <div class="col-sm-4">
            <input type="file" class="form-control" name="avatar" />
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#fileForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            avatar: {
                validators: {
                    file: {
                        extension: 'jpeg,png',
                        type: 'image/jpeg,image/png',
                        maxSize: 2048 * 1024,
                        message: 'The selected file is not valid'
                    }
                }
            }
        }
    });
});