如果美国被选为另一个下拉列表中的国家,则验证一个州下拉列表



需要一些建议我正在尝试编写一个验证器,该验证器只有在下拉列表中选择特定值时才会启动。

我在这个表格上有两个下拉列表,一个是国家,另一个是美国,国家下拉列表只在从国家下拉列表中选择美国时显示。

我需要一个验证器,只有当美国被选为国家时,才能使州下拉列表成为必填字段。

作为背景信息,这是一个MVC3 Web应用程序,States下拉列表的显示/隐藏代码是JQuery。

另一种选择是将规则动态添加到jQuery中进行验证。但是,您还需要在服务器端检查此自定义逻辑。您可以在控制器中执行此操作,或者理想情况下,您的VieWModel将实现IValidateableObject,以检查country="usa"是否需要country。

使用jQuery的.rules.add和.remove:

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

所以你可以做一些类似的事情:


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

和您的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
}

You could write a custom validation attribute:

public class RequiredIfAttribute : ValidationAttribute
{
    public RequiredIfAttribute(string otherProperty, object otherPropertyValue)
    {
        OtherProperty = otherProperty;
        OtherPropertyValue = otherPropertyValue;
    }
    public string OtherProperty { get; private set; }
    public object OtherPropertyValue { get; private set; }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(OtherProperty);
        if (property == null)
        {
            return new ValidationResult(string.Format("Unknown property: {0}", OtherProperty));
        }
        object otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
        if (!object.Equals(OtherPropertyValue, otherPropertyValue))
        {
            return null;
        }
        if (value != null)
        {
            return null;
        }
        return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
    }
}

现在你可以有一个视图模型:

public class MyViewModel
{
    public string Country { get; set; }
    [RequiredIf("Country", "usa", ErrorMessage = "Please select a state")]
    public string State { get; set; }
    public IEnumerable<SelectListItem> Countries
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "fr", Text = "France" },
                new SelectListItem { Value = "usa", Text = "United States" },
                new SelectListItem { Value = "spa", Text = "Spain" },
            };
        }
    }
    public IEnumerable<SelectListItem> States
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "al", Text = "Alabama" },
                new SelectListItem { Value = "ak", Text = "Alaska" },
                new SelectListItem { Value = "az", Text = "Arizona" },
            };
        }
    }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }
    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

和一个视图:

@model MyViewModel
@using (Html.BeginForm())
{
    <div>
        @Html.DropDownListFor(x => x.Country, Model.Countries, "-- Country --")
        @Html.ValidationMessageFor(x => x.Country)
    </div>
    <div>
        @Html.DropDownListFor(x => x.State, Model.States, "-- State --")
        @Html.ValidationMessageFor(x => x.State)
    </div>
    <button type="submit">OK</button>
}

您可能还发现验证属性的Foolproof包非常有用。

最新更新