Check file upload control using jquery

How to check asp.net FileUpload control using jquery. I need to check two things: FileUpload should not be empty when the user clicks the ok button, and it should contain only excel and csv files.

Please, help.

+6
source share
2 answers

You can check for the 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 can check for the 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 also need to check on the server, this code is just a courtesy for users included in JavaScript.

Also choose something better than alert() . This is not the most convenient way to report an error.

+6
source

You can make jQuery validation plugin for this:

 $(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 } } }); }); 
+2
source

Source: https://habr.com/ru/post/889924/


All Articles