使用jquery验证文件上传控制 [英] Validation of File Upload Control using jquery

查看:58
本文介绍了使用jquery验证文件上传控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jquery验证asp.net FileUpload控件. 我需要验证两件事,当用户单击确定"按钮时,FileUpload不应为空,并且应仅包含excel和csv文件.

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.

请帮助.

推荐答案

您可以在扩展程序上进行验证...

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

});

...或者您可以验证mime类型.

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

});

当然,您也需要在服务器上进行验证,此代码只是对启用JavaScript的用户的礼貌.

Of course, you need to validate on the server too, this code is just a courtesy to JavaScript enabled users.

此外,选择比alert()更好的东西.它们不是报告错误的最人性化的方式.

Also, choose something better than alert(). They are not the most user friendly way of reporting an error.

这篇关于使用jquery验证文件上传控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆