Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of File Upload Control using jquery

Tags:

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 files.

please help.

like image 409
chinnu Avatar asked Jun 07 '11 06:06

chinnu


2 Answers

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.

like image 85
alex Avatar answered Sep 21 '22 13:09

alex


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
            }
        }
    });
});
like image 23
Abdul Kader Avatar answered Sep 19 '22 13:09

Abdul Kader