使用jQuery Validate插件进行文件上传验证

lak*_*nga 3 jquery file-upload jquery-validate twitter-bootstrap

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

这是我的代码

 <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();
 }
});
});
Run Code Online (Sandbox Code Playgroud)

这是我的jquery

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

Spa*_*rky 14

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


你的代码:

<input type="file" name="fupl" style="display:none;margin-top:10px" id="fup"/>
Run Code Online (Sandbox Code Playgroud)

您的文件上传字段设置为display:none;,默认情况下插件将忽略所有隐藏字段.

使用该ignore: []选项可禁用此功能.

$(document).ready(function () {

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

});
Run Code Online (Sandbox Code Playgroud)

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


编辑:不确定OP想要采用哪种方式,但是当重新隐藏文件上载字段时,以下演示会隐藏任何待处理的错误消息.

$("#fup").next('label.error').hide();
Run Code Online (Sandbox Code Playgroud)

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