Onchange Jquery Validation For File Type
Here is my Fiddle What i have is to display the image name near the upload text in the onchange event. Here i need to have the validation on the onchange and it should display the
Solution 1:
<!doctype html><htmllang="en"><head><metacharset="utf-8"><title>Validation</title><scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script><styletype="text/css">labelinput[type="file"]
{
display: block;
margin-top: -20px;
opacity: 0;
}
</style><script>
$(window).ready(function() {
$(document).delegate('#Upload','change',function(){
var s=$(this).val();
functionstringEndsWithValidExtension(stringToCheck, acceptableExtensionsArray, required) {
if (required == false && stringToCheck.length == 0) { returntrue; }
for (var i = 0; i < acceptableExtensionsArray.length; i++) {
if (stringToCheck.toLowerCase().endsWith(acceptableExtensionsArray[i].toLowerCase())) { returntrue; }
}
returnfalse;
}
$('#spanFileName').html(s);
setTimeout(function(){
$('#spanFileName').html("");
},15000)
String.prototype.startsWith = function (str) { return (this.match("^" + str) == str) }
String.prototype.endsWith = function (str) { return (this.match(str + "$") == str) }
alert(s);
if (!stringEndsWithValidExtension($("[id*='Upload']").val(), [".png", ".jpeg", ".jpg", ".bmp"], false)) {
alert("Photo only allows file types of PNG, JPG and BMP.");
returnfalse;
}
returntrue;
});
});
</script></head><body>
Upload<inputid='Upload'type="file"style="display:block;margin-top: -20px;opacity: 0;" ><spanid='spanFileName'></span></body></html>
Solution 2:
The solution is very simple using JQuery
Have your HTML as
Upload<input type="file"id="fileUpload" style="display:block;margin-top: -20px;opacity: 0;" >
<span id='spanFileName'></span>
and then using Jquery
$('#fileUpload').on("change",function () {
var fileExtension = ['jpeg', 'jpg'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
// alert("Only '.jpeg','.jpg' formats are allowed.");
$('#spanFileName').html(this.value);
$('#spanFileName').html("Only '.jpeg','.jpg' formats are allowed.");
}
else {
$('#spanFileName').html(this.value);
//do what ever you want
}
})
here is the working sample http://jsfiddle.net/c9sbmdv5/3/
Post a Comment for "Onchange Jquery Validation For File Type"