Demo

jqExtension – jQuery file type validation plugin

If you have contact form or job apply form in your website, then you might have FILE field in the form. Where you are actually asking user to upload/submit valid file. If it is a job apply form then you would be asking to submit .doc, .docx, .rtf, .odt files. With jQuery it is easy to check and validate which file/s users are allowed to submit.

<script>
  ;(function($) {
    $('input#submit').click(function() {
      var file = $('input[type="file"]').val();
      var exts = ['doc','docx','rtf','odt'];
      // first check if file field has any value
      if ( file ) {
        // split file name at dot
        var get_ext = file.split('.');
        // reverse name to check extension
        get_ext = get_ext.reverse();
        // check file type is valid as given in 'exts' array
        if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){
          alert( 'Allowed extension!' );
        } else {
          alert( 'Invalid file!' );
        }
      }
    });
  })(jQuery);
</script>

You can also use chaining method to get the extension such as

var get_ext = file.split('.').reverse()[0].toLowerCase();

To check image file types you can put extensions like .jpg, .jpeg, .gif, .png, .bmp in ‘exts‘ array. Rest everything will be same.

Demo

 

To simply this file type extension check, we have written a jQuery plugin for you. Take a look at jqExtension.js and its live demo.

jqExtension – jQuery file type validation plugin

 

You might also like