0

需要一些建议我正在尝试编写一个仅在选择下拉列表中的特定值时触发的验证器。

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

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

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

4

2 回答 2

1

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

使用 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
}

于 2012-09-10T14:12:27.413 回答
0

您可以编写自定义验证属性:

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验证属性包很有用。

于 2012-09-10T13:16:09.677 回答