使用 jQuery Validate 插件进行文件上传验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15147793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File upload validation with jQuery Validate plugin
提问by lakshganga
I have a weird problem.I have a form with a file upload and few other textarea .each and every field is required.so basically when few fields are left blank,the validation works fine but if and only if the file upload is left blank,the form gets submitted.
我有一个奇怪的问题。我有一个带有文件上传和其他几个 textarea 的表单。每个字段都是必需的。所以基本上当很少有字段留空时,验证工作正常,但当且仅当文件上传留空时,表单被提交。
Here is my code
这是我的代码
<li >
<p>
<label for="rad">radio label:
</label><br>
<input type="radio" name="rad" value="yes" style="width:20px"> Yes </input>
<input type="radio" name="rad" value="no" style="width:20px"> 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"> <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();
}
});
});
and this my jquery
这是我的 jquery
$('#form').validate({
rules: {
fupl: {
required: true,
accept:'docx|doc'
},
回答by Sparky
Your code appears to be working just fine. Hidden fields are ignored by the Validate plugin. However, when you show the file upload field via radio button, it will validate and display the error message. See: http://jsfiddle.net/y5ghU/
您的代码似乎工作得很好。Validate 插件会忽略隐藏字段。但是,当您通过单选按钮显示文件上传字段时,它将验证并显示错误消息。见:http: //jsfiddle.net/y5ghU/
Your code:
您的代码:
<input type="file" name="fupl" style="display:none;margin-top:10px" id="fup"/>
Your file upload field is set to display:none;
and the plugin will ignore all hidden fields by default.
您的文件上传字段设置为display:none;
默认情况下插件将忽略所有隐藏字段。
Use the ignore: []
option to disable this feature.
使用该ignore: []
选项禁用此功能。
$(document).ready(function () {
$('#form').validate({
ignore: [],
rules: {
fupl: {
required: true,
accept: 'docx|doc'
}
}
});
});
DEMO: http://jsfiddle.net/ptV35/
演示:http: //jsfiddle.net/ptV35/
EDIT: Not really sure which way the OP wants to go, but the following demo hides any pending error message when the file upload field is re-hidden.
编辑:不太确定 OP 想要走哪条路,但是当重新隐藏文件上传字段时,以下演示隐藏了任何未决的错误消息。
$("#fup").next('label.error').hide();