validate a state dropdownlist if the US is selected as a country in another dropdownlist

Need some advice I am trying to write a validator which only fires when a specific value in a dropdownlist is selected.

I have two drop down lists on this form one for Countries and the other for US States, the States dropdownlist only shows when the United States is selected from the Countries dropdownlist.

I need a validator that makes the State dropdownlist list a required field only if the United States is selected as a country.

As background information this a MVC3 Web Application and the show/hide code for the States dropdownlist is JQuery.

Answers


Another alternative is to dynamically add the rule to jQuery for validation. You would need to check on the server side this custom logic as well however. You can do this in your controller, or ideally your VieWModel would implement IValidateableObject to check if country="usa" then county is required.

Use jQuery's .rules.add and .remove:

http://docs.jquery.com/Plugins/Validation/rules#.22remove.22rules

So you could do something along the lines of:


$(document).ready(function() {
    $("#country").change(function(){
        if($(this).val()=="usa")
        {
          $("#yourCountyDropDown").rules("add", {
           required: true,
           messages: {
             required: "County is required"
           }
          });
        }
        else
        {
          $("#yourCountyDropDown").rules("remove");
        }
    });
});

and for your ViewModel

public class WhateverYourObjectNameCreateViewModel : IValidatableObject
{
       #region Validation
        public IEnumerable Validate(ValidationContext validationContext)
        {
            if (this.Country=="USA" && string.IsNullOrEmpty(this.County))
            {
                yield return new ValidationResult("County is required");
            }
        }
        #endregion
}


Need Your Help

X11 errors with pygtk on Mac OS X 10.5.8

python pygtk x11 osx-leopard

I have a python program that implements pygtk for GUI. I have it running successfully on some MAC computers running os 10.6.*, after installing pygtk with macports. I have just installed pygtk on...

Scala function to get all sorted subsets of size k

function scala permutation sorted

I am given a set of size L and want to generate every sorted subset of size k.