jQuery.Validate条件验证RadioButton和DropDownList [英] jQuery.Validate Conditional Validation RadioButton and DropDownList

查看:87
本文介绍了jQuery.Validate条件验证RadioButton和DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一些验证,因此,如果选中是"单选按钮,则需要验证另一个控件(下拉列表),以确保未将其设置为列表中的默认第一项请选择...".

I am trying to set up some validation, so that if the 'Yes' radio button is checked another control, which is a drop down list needs to be validated to ensure it is not set to the default first entry in the list "Please Select...".

我尝试了许多组合,但无法使其正常工作.验证消息显示该复选框是否已选中.

I have tried many combinations but have not been able to get this to work. The validation message shows whether the check box is checked or not.

这里有一些代码!

这是我使用的自定义方法,可用来验证我的下拉列表. (这对于简单的DDL验证很有效)

This is a custom method I have which I use to validate my drop down lists. (This works fine for simple DDL validation)

    $.validator.addMethod(
    "selectNone",
    function(value, element) {
        return this.optional(element) || element.value != "Please Select...";
    },
    "Please select an option."
);

要基于复选框进行验证,我已在表单中添加了一条规则

To do the validation based on the checkbox I have added a rule to the form

$(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>

任何想法都将不胜感激.

Any ideas would be very much appreciated.

非常感谢

推荐答案

只要第一个下拉列表选项具有空白值(<option value="">some text</option>),,以下规则将起作用:

As long as the first drop-down list option has a blank value (<option value="">some text</option>), the following rule will work:

rules: {
  NCBYears: {
    required: function(element) {
      return $("input:radio[name='PreviousInsurance']:checked").val() == 'yes';
    }
  }                
}

来自: http://docs.jquery.com/Plugins/验证/方法/必需的#dependency-expression

这篇关于jQuery.Validate条件验证RadioButton和DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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