views:

5233

answers:

1

Hi,

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

+5  A: 

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

ScottE
But it doesn't it has a "Please Select..." and this has to remain
andyJ
Only the option value has to be blank, not the text. If the control can't do this, use jquery to change the value to blank on ready.
ScottE