0

我的模型如下

[Validator(typeof(PersonValidator))]
public class Person
{
    public string Id { get; set; }
    public string Name { get; set; }

}

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {

      RuleFor(x => x.Name).Length(4, 10)
        .When(per => per.Id.ToUpper() == "FOO");
    }
}

我的控制器如下

 public class HomeController : Controller
{
    [HttpPost]
    public ActionResult PersonAction(Person p)
    {

        if (ModelState.IsValid)
        {
            return View();
        }
        else
        {
            return View();
        }
    }
}

我希望使用 Fluent Validation 设置以下验证

  1. 如果Id == 'foo',那么Name应该有它的Length验证
  2. 如果Id !== 'foo',那么Name应该有Length验证

但是长度验证似乎总是被应用。即不管Id的值是多少,我错过了什么?

4

1 回答 1

1
When(x => string.Equals(x.Id, "foo", System.StringComparison.CurrentCultureIgnoreCase), () => 
{
   RuleFor(x => x.Name).Length(4, 10).WithMessage([YOUR MESSAGE]);
});
于 2016-06-13T15:45:34.957 回答