我正在尝试设置一些验证,这样如果选中“是”单选按钮,则需要验证另一个控件,即下拉列表,以确保它未设置为列表中的默认第一个条目“请选择…“.
我尝试了很多组合,但还没能让它发挥作用.验证消息显示是否选中了复选框.
这是一些代码!
这是我用来验证下拉列表的自定义方法. (这适用于简单的DDL验证)
$.validator.addMethod( "selectNone",function(value,element) { return this.optional(element) || element.value != "Please Select..."; },"Please select an option." );
要根据复选框进行验证,我已在表单中添加了规则
$(document).ready(function() { var validator = $("#BuildingsCoverForm").validate({ rules: { NCBYears: { selectNone: function(element) { return $("*[name='PrevIoUsInsurance']")[0].checked; } } },messages: { NCBYears: { selectNone: "This field is required" } } }); });
这是控件.
<p> <label for="PrevIoUsInsurance" class="halfstretch">Do you have any prevIoUs insurance?</label> <%= Html.YesNoControl("PrevIoUsInsurance",Model.PrevIoUsInsurance)%> </p> <p> <label for="NCBYears" class="halfstretch">Building No Claim Bonus</label> <%= Html.DropDownList("NCBYears",ViewData["NCBYears"] as SelectList)%> </p>
任何想法将非常感谢.
非常感谢
解决方法
只要第一个下拉列表选项具有空值(< option value =“”>某些文本< / option>),以下规则就可以使用:
rules: { NCBYears: { required: function(element) { return $("input:radio[name='PrevIoUsInsurance']:checked").val() == 'yes'; } } }
来自:http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression