validate a drop-down status list if the United States is selected as a country in another drop-down list

advertisements

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.


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
}