asp.net-mvc - Fluent 验证 When 子句

标签 asp.net-mvc fluentvalidation

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

这是我的 View 模型类

[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");
    }
}

我的 Razor View

<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 对客户端验证的支持有限:

Note that FluentValidation will also work with ASP.NET MVC's client-side validation, but not all rules are supported. For example, any rules defined using a condition (with When/Unless), custom validators, or calls to Must will not run on the client side. The following validators are supported on the client:

  • NotNull/NotEmpty
  • Matches (regex)
  • InclusiveBetween (range)
  • CreditCard
  • Email
  • EqualTo (cross-property equality comparison)
  • Length

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

关于asp.net-mvc - Fluent 验证 When 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084892/

相关文章:

asp.net-mvc - Azure 应用程序见解 - AI(内部): 24 message:"Missing required field specification

asp.net-mvc - MVC5 比较两个可为空的日期与流畅的验证

c# - 如何单元测试简单的属性有验证器集?

c# - 模拟子验证器时 FluentValidation 抛出 NullReference 异常

javascript - SignalR 不适用于 Chrome 和 Internet Explorer

asp.net-mvc - 将 MVC 身份验证与 SignalR v2.x 结合使用

javascript - FileContentResult - 防止浏览器缓存图像

c# - 导航属性和避免循环引用

c# - Mediatr:单元测试行为/验证

c# - 使用父模型值的子模型验证。流利的验证。 MVC4