【问题标题】:Fluent Validation When ClauseFluent Validation When 子句
【发布时间】:2016-10-17 11:10:35
【问题描述】:

我正在开发一个 ASP.Net MVC 5 Web 应用程序,我正在使用 FluentValidation (https://github.com/JeremySkinner/FluentValidation) 进行验证。我在使用 .When() 子句时遇到了问题,因为我无法让它工作。但是,我可以使用 .NotEmpty() 和 .Length() 子句之类的方法。

这是我的 Viewmodel 类

[Validator(typeof(ViewModelEmployerValidator))]
public class ViewModelEmployer
{
    public string CurrentLineManagerEmail { get; set; }
    public string NewLineManagerEmail { get; set; }
}

public class ViewModelEmployerValidator : AbstractValidator<ViewModelEmployer>
{
    public ViewModelEmployerValidator()
    {
        RuleFor(x => x.NewLineManagerEmail).NotEmpty().When(x => x.CurrentLineManagerEmail == "").WithMessage("Please enter your new Line Manager Email");
    }
}

我的剃刀视图

<div>
    <div class="form-group">
        @Html.TextBoxFor(model => model.CurrentLineManagerEmail, new { @class = "form-control", placeholder = "Current Line Manager Email" })
        @Html.ValidationMessageFor(model => model.CurrentLineManagerEmail)
    </div>
</div>

<div>
    <div class="form-group">
        @Html.TextBoxFor(model => model.NewLineManagerEmail, new { @class = "form-control", placeholder = "New Line Manager Email" })
        @Html.ValidationMessageFor(model => model.NewLineManagerEmail)
    </div>
</div>

当用户提交表单时,即使文本框 CurrentLineManagerEmail 为空,.When() 验证也会选择规则并要求用户输入新的直线经理电子邮件。

但是,如上所述,.NotEmpty() 和 .Length() 之类的或它们自己的工作正常。只有当我添加 .When() 子句时,验证似乎才会失败。

有人可以帮忙吗?

谢谢。

【问题讨论】:

  • 您是否期待客户端验证(FluentValidation 不支持 .When()jquery.validate.unobtrusive.js
  • When 在客户端不起作用,但在服务器端,我没有任何问题
  • @StephenMuecke 嗨,斯蒂芬。是的,我期待使用 .When() 进行客户端验证。反正有这个吗?
  • 简短回答是否定的。来自docs请注意,FluentValidation 也可以与 ASP.NET MVC 的客户端验证一起使用,但并非所有规则都受支持。例如,使用条件(使用 When/Unless)、自定义验证器或对 Must 的调用定义的任何规则都不会在客户端运行。
  • 看看this link。默认情况下,客户端仅支持部分验证。您也可以write custom code 支持其他验证规则,但我认为您不能为When 做到这一点。

标签: asp.net-mvc fluentvalidation


【解决方案1】:

FluentValidation 对客户端验证的支持有限:

请注意,FluentValidation 也适用于 ASP.NET MVC 的客户端验证,但并非所有规则都受支持。例如,使用条件(使用 When/Unless)、自定义验证器或对 Must 的调用定义的任何规则都不会在客户端运行。客户端支持以下验证器:

  • NotNull/NotEmpty
  • 匹配(正则表达式)
  • InclusiveBetween(范围)
  • 信用卡
  • 电子邮件
  • EqualTo(跨属性相等比较)
  • 长度

(来自https://fluentvalidation.codeplex.com/wikipage?title=mvc

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 2012-09-17
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    相关资源
    最近更新 更多