【问题标题】:File upload validation with jQuery Validate plugin使用 jQuery Validate 插件进行文件上传验证
【发布时间】:2013-02-28 23:37:44
【问题描述】:

我有一个奇怪的问题。我有一个带有文件上传和其他几个文本区域的表单。每个字段都是必需的。所以基本上当几个字段留空时,验证工作正常,但当且仅当文件上传留空,表单被提交。

这是我的代码

 <li >
  <p>
    <label for="rad">radio label:
    </label><br>

   <input type="radio" name="rad" value="yes" style="width:20px">&nbsp; Yes&nbsp;&nbsp;</input>
   <input type="radio" name="rad" value="no" style="width:20px">&nbsp; No</input><br/>
   <label for="cv" class="error" style="display:none">This field is required</label>
   </p>
    <p>
    <input type="file" name="fupl" style="display:none;margin-top:10px" id="fup"/>
    <label for="fupl" class="error" style="display:none;color:red">This field is required</label>
    </p>
    </li>
    <br>
    <li>
  <label>checkbox label
  </label><br><br>
 <input type="checkbox" name="cb" value="tick" style="width:20px">&nbsp;&nbsp;   <small>checkbox field<small></input><br>                                          <label for="fee" class="error" style="display:none">This field is required</label>
    </li>
  <br><li>
 <input type="submit" class="button" value="SUBMIT" style="float:right"/>
 </li>
 <script>
 $(document).ready(function()
 {
 $("input[type='radio']").change(function(){
if($(this).val()=="yes")
 {
 $("#fup").show();
 }
else
{
  $("#fup").hide();
 }
});
});

这是我的 jquery

  $('#form').validate({
rules: {    
fupl: {
    required: true,
    accept:'docx|doc'
    },    

【问题讨论】:

  • 您在上面的代码中没有显示form 标记。

标签: jquery file-upload twitter-bootstrap jquery-validate


【解决方案1】:

您的代码似乎运行良好。 Validate 插件会忽略隐藏字段。但是,当您通过单选按钮显示文件上传字段时,它将验证并显示错误消息。见:http://jsfiddle.net/y5ghU/


您的代码:

<input type="file" name="fupl" style="display:none;margin-top:10px" id="fup"/>

您的文件上传字段设置为display:none;,插件默认会忽略所有隐藏字段。

使用ignore: [] 选项禁用此功能。

$(document).ready(function () {

    $('#form').validate({
        ignore: [],
        rules: {
            fupl: {
                required: true,
                accept: 'docx|doc'
            }
        }
    });

});

演示:http://jsfiddle.net/ptV35/


编辑:不太确定 OP 想要走哪条路,但是当文件上传字段被重新隐藏时,以下演示会隐藏任何待处理的错误消息。

$("#fup").next('label.error').hide();

http://jsfiddle.net/y5ghU/4/

【讨论】:

  • 谢谢你的工作。但就像验证后不久,文件上传字段消失了,只显示错误消息。我也需要显示文件上传字段。
  • 而且,即使我点击“否”,它也说该字段是必填项。
  • @lakshganga,您可以添加$("#fup").next('label.error').hide(); 来隐藏标签。见:jsfiddle.net/y5ghU/4
猜你喜欢
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多