我的模型如下
[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 设置以下验证
- 如果Id == 'foo',那么Name应该有它的Length验证
- 如果Id !== 'foo',那么Name不应该有Length验证
但是长度验证似乎总是被应用。即不管Id的值是多少,我错过了什么?