Validation of File Upload Control using jquery
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 fil开发者_如何转开发es.
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
}
}
});
});
精彩评论