Html:
<input type="file" id="file" name="file" />
<span id="valFile" class=""></span> // span for showing error message.
CSS:
.field-validation-error {
color: #f00;
}
.field-validation-valid {
display: none;
}
.input-validation-error {
border: 1px solid #f00;
background-color: #fee;
}
JQuery Snippet:
$(document).ready(function( )
{
//Changing the Error message of the File Upload and checking the File size and File type.
$("#file").change(function () {
$("#valFile").html("Please select file."); // Default Error Message
var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'doc', 'docx', 'pdf'];
if ($(this).val() != "") { //checking wheather the file uploader is empty or not
//Checking the File type
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
$(this).addClass("input-validation-error").removeClass("valid");
$("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
.html("Invalid Filetype(only image files/doc/docx/pdf)");
}
else {
$(this).removeClass("input-validation-error").addClass("valid");
$("#valFile").removeClass("field-validation-error").addClass("field-validation-valid");
if ((this.files[0].size > 4194304) && ($(this).val() != '')) {
$(this).addClass("input-validation-error").removeClass("valid");
$("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
.html("File size exceeded 4MB");
}
}
} else {
$(this).addClass("input-validation-error").removeClass("valid");
$("#valFile").addClass("field-validation-error").removeClass("field-validation-valid");
}
});
});
Happy Coding!
No comments:
Post a Comment