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.
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
- jQuery validationEngine: Extended jQuery form validations
- jQuery Plugin: ResetFormFields
- jQuery Equal Height Plugin
- jQuery Ad Gallery – Extended Photo Gallery Slideshow
- Autoplay embeded video on any event with jQuery
- Simple and easy Cookie based jQuery tabs
- Simple jQuery Single Level Drop Down Menu
- AngularJS in 20 minutes
- Advanced Search in AngularJS – Part 1
- Javascript Random Color
March 7, 2013 at 5:16 pm
Nice Boss…
January 21, 2014 at 10:22 am
Thank you man
March 26, 2014 at 3:05 am
Looks very good working 100% and happy news i have edited this code to work for more than one file upload in the same form..
function file_vali(element_id)
{
var file = $(‘#’+element_id).val();
var exts = [‘doc’,’docx’,’pdf’];
// 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 ){
document.getElementById(element_id).style.border = “1px solid white”;
alert( ‘Allowed extension!’ );
} else {
alert( ‘Invalid file!’ );
document.getElementById(element_id).style.border = “1px solid red”;
document.getElementById(element_id).focus();
}
}
}
Sorry i don’t own any website to give u live demo but this one will work if admin consider this code to live demo it will be really helpful to all…
May 19, 2015 at 2:35 am
Thank you, Good work !