Fluent 验证 When 子句

Fluent Validation When Clause

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

这是我的视图模型class

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

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