Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.Validate Conditional Validation RadioButton and 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.

Heres some code!

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"
                }
            }
        });
    });

And here are the controls.

<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.

Many Thanks

like image 461
andyJ Avatar asked Jul 05 '09 17:07

andyJ


2 Answers

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';
    }
  }                
}

from: http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression

like image 175
ScottE Avatar answered Nov 15 '22 21:11

ScottE


ScottE is correct. I have a dropdownlist populated from a database and I just appended an item at the very top of the list and gave it a value of "". When you validate the input just validate against the dropdownlist being blank. You could also hard code the list if it never changes and add an item to the top with a blank value, example below.

_example.Add(new SelectListItem { Text = "Select Example", Value = ""});
like image 39
chad Avatar answered Nov 15 '22 22:11

chad