Hii,
File Validator is a function used when we want to restrict the type of file uploaded.
Using File validator we can easily get file Info for each file uploaded.
If uploaded file is not as per the required format a validator function will throw it an exception with some error message.
File validator is mostly used in contact form or job apply form in website where we want user to upload valid file, like for job apply form we require image files with extension such as .jpg , .jpeg, .bmp , .gif, .png and for document files with extension such as doc, docx, txt, pdf, rtf are required.
Following are the examples of file validation:
CSS: CSS will be common for both the examples below
label {display: block;font-weight: bold;margin-bottom:15px;text-decoration:underline;}
Example 1: Image File validation
HTML:
<form action="#" method="post" enctype="multipart/form-data">
<div>
<label for="image">Upload image (jpeg, jpg , bmp , gif, png only)</label>
<input type="file" name="image" id="image" />
</div>
</form>
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', 'bmp' , 'gif' , 'png' ],
success: function() {
alert('Successfully uploaded');
},
error: function() {
alert('File type not matched');
}
});
});
Example 2: Document File validation
HTML:
<form action="#" method="post" enctype="multipart/form-data">
<div>
<label for="document">Upload file (doc, docx, txt, pdf, rtf only)</label>
<input type="file" name="document" id="document" />
</div>
</form>
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() {
$('#document').checkFileType({
allowedExtensions: ['doc', 'docx', 'txt', 'pdf', 'rtf'],
success: function() {
alert('Successfully uploaded');
},
error: function() {
alert('File type not matched');
}
});
});
0 Comment(s)