6

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.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

9 Comments

I would add a \. in there also as a file named test.zxl will match
@alex psycic? On the second one i would testto make sure there were any returned from $('input[type=file]').prop('files') first
hi alex, <asp:FileUpload ID="fileupload" runat="server" /> <asp:Button ID="btnOK" runat="server" Text="OK" Width="60px" CausesValidation="False" /> this is the button and fileupload control im using. i used the first code stated above and i replaced [type=file] to [type=fileupload] and then what i need to change for button click. when i click the button nothing is firing
@chinnu The selectors I used are generic. They will need to be changed to suit your markup.
@chinnu The selector for the form and the file input.
|
2

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
            }
        }
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.