JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<div id="message"></div>
<table>
<tr>
<td>
<label>Insert File</label>
</td>
<td>
<input type="file" name="filen" id="filen" />
</td>
</tr>
</table>
JavaScript
$.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).wrap('<form>').closest('form').get(0).reset();
$(this).unwrap('<form>');
$(this).focus();
} else {
options.success();
}
});
});
};
$(function() {
$('#filen').checkFileType({
allowedExtensions: ['jpg', 'jpeg', 'png', 'bmp'],
success: function() {
$("#message").text("Valid image").fadeIn();
},
error: function() {
$("#message").text('Error: Please insert valid image file with following extensions .jpg .jpeg .png .bmp').fadeIn();
}
});
});