【问题标题】:ASP:NET MVC 4 dynamic validation of a property depending of the current value of another propertyASP:NET MVC 4 根据另一个属性的当前值动态验证一个属性
【发布时间】:2014-07-31 13:34:07
【问题描述】:

我无法找到一种方法来根据同一模型中另一个属性的当前值动态验证属性。我进行了很多搜索,但找不到答案或类似示例。

在我的模型中,我有一个 zip code 属性和一个 countryID 属性。在每个不同国家的数据库中,我有一个不同的正则表达式来验证邮政编码。 然后使用 countryID 我可以从数据库中获取适当的正则表达式来验证相应国家/地区的邮政编码

所以在我的模型中,根据当前 countryID 的值,我希望验证 zip 字段。

我尝试创建自定义验证属性“ZipValidation(countryID)”,但在模型中它不允许我将另一个属性的值作为参数:

public class AddressViewModel
{
    ...
    [Display(Name = "Country ID")]
    public Guid? countryID { get; set; }

    [Required]
    //[ZipValidation(countryID)] does not compile because of the countryID
    [Display(Name = "Zip")]
    public string zip { get; set; }

}

知道如何实现吗?

【问题讨论】:

标签: c# asp.net-mvc validation


【解决方案1】:

我终于解决了这个问题,正如 Jonesy 建议的那样,使用 [Remote] 验证属性,并在我的控制器中使用 Json 和 Ajax。是这样的:

public class AddressViewChannelModel
{
    ....
    [Display(Name = "CountryID")]
    public Guid? countryID  { get; set; }

    [Required]
    [Remote("ValidateZipCode", "Address", AdditionalFields = "countryID")]
    [Display(Name = "Zip")]
    public string zip { get; set; }
}

public class AddressController : Controller
{
  ...
    public JsonResult ValidateZipCode(string zip, string countryID)
    {
        ValidationRequest request = new ValidationRequest();
        request.CountryID = Guid.Parse(countryID);
        request.Zip = zip;

        ValidationResponse response = new ValidationResponse();
        response = _addressApi.ZipValidation(request);

        if(response.IsSuccessful == false)
        {
            return Json("Not a valid zip code for your chosen country!"),  JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }
}

【讨论】:

    【解决方案2】:

    您需要在这里创建自己的验证属性... 正如罗德里戈所说,在属性的构造函数中,您将传递您的验证属性也将使用的属性的名称,在您的情况下为 countryID。然后您将使用反射来获取该属性的值并知道您可以进行验证。这一切都会很好,即使有一点运气和很多技巧,您也可以使其可重用,但是如果您想要客户端验证,您需要自己实现它。这是一个很长的故事,我看到你已经从哪里得到了适当的参考来理解整个过程,所以我将把我从中学到的东西给你:Flexible Conditional Validation with ASP.NET MVC

    【讨论】:

      【解决方案3】:

      这有点低技术,如果您有时间和意愿,您可能应该使用验证属性进行调查,但为了完整起见,这是一个可行的解决方案。在您的帖子操作中:

      [HttpPost]
      public ActionResult MyAwesomePostAction(AddressViewModel model)
      {
          if (!ValidationUtil.IsValidZipCode(model.zip, model.countryID))
          {
              ModelState.AddModelError("zip", "Not a valid zip code for your chosen country.");
          }
      
          if (ModelState.IsValid)
          {
              ...
          }
      
          return View(model);
      }
      

      我假设了一些库,您可以在其中将验证存储在控制器之外。这样一来,您的操作中就不会有很多无关代码,如果您需要再次执行此操作,则不必重复验证逻辑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 2018-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多