How to validate asp.net FileUpload control using jquery. I need to validate two things, FileUpload should not be empty when user clicks ok button and it should contain only excel and csv files.
please help.
You could validate on extension...
$('form').submit(function(event) {
var file = $('input[type=file]').val();
if ( ! file) {
alert('The file is required.');
event.preventDefault();
return;
}
if (file.match(/\.(?:csv|xl)$/)) {
alert('CSV or Excel files only!');
event.preventDefault();
}
});
...or you could validate on mime type.
$('form').submit(function(event) {
var file = $('input[type=file]').prop('files')[0];
if ( ! file) {
alert('The file is required.');
event.preventDefault();
return;
}
var mime = file.type;
if (mime != 'text/csv' || mime != 'application/vnd.ms-excel') {
alert('CSV or Excel files only!');
event.preventDefault();
}
});
Of course, you need to validate on the server too, this code is just a courtesy to JavaScript enabled users.
Also, choose something better than alert()
. They are not the most user friendly way of reporting an error.
You can make the jQuery validation plugin to do that for you:
$(document).ready(function() {
$("#form").validate({
rules: {
MyFile: {
required: false,
accept: "jpg|jpeg|png|gif"
}
}
});
$("#submit").click(function() {
var file = $('#MyFile').val();
if($("#create_form").valid()) {
if(file != '') {
// do something
}
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With