我的模型如下
[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验证设置以下验证
- 如果Id='foo',则Name应进行Length验证
- 如果Id!==='foo’,则名称应NOT具有长度验证
但Lenght验证似乎总是得到应用。即,不管Id的值是多少,我缺少什么?
When(x => string.Equals(x.Id, "foo", System.StringComparison.CurrentCultureIgnoreCase), () =>
{
RuleFor(x => x.Name).Length(4, 10).WithMessage([YOUR MESSAGE]);
});