这是我第一次尝试实现 FluentValidation,因为我需要涵盖复杂的验证场景。
我试图验证的类具有大量属性、复杂对象和多个集合。
我没有遇到验证主类的属性的问题,甚至检查集合是否不为空,但在验证每个集合中的对象属性时确实遇到了问题。
为了实现这一点,我遵循了此处记录的示例(检查“重新使用集合验证器”):http://fluidation.codeplex.com/wikipage?title=creatingavalidator http://fluentvalidation.codeplex.com/wikipage?title=creatingavalidator
这些是我的模型类(减少以提高可读性)
public class Caso
{
public int Id { get; set; }
public string Descripcion { get; set; }
public List<Medicamento> Medicamentos { get; set; }
}
public class Medicamento
{
public int Id { get; set; }
public string Nombre { get; set; }
}
这些是验证器类:
public class CasoValidator : AbstractValidator<CasoAdverso>
{
public CasoValidator()
{
RuleSet("Iniciar", () =>
{
// Validated OK
RuleFor(x => x.Descripcion).NotEmpty();
// Validated OK
RuleFor(x => x.Medicamentos).Must(x => x != null && x.Count > 0).WithMessage("No puede iniciar un caso sin medicamentos cargados");
RuleFor(x => x.Medicamentos).SetCollectionValidator(new MedicamentoValidator());
});
}
}
public class MedicamentoValidator : AbstractValidator<Medicamento>
{
public MedicamentoValidator()
{
// NOT Validated. Even if the object property is empty the error message doesn't appear. I also checked using "NotNull" and "NotEmpty" clauses
RuleFor(x => x.Nombre).NotNull().WithMessage("Debe especificar un nombre");
}
}
(注意:我使用规则集是因为不同的验证模式取决于工作流程中的文档状态)
我正在从控制器手动执行验证(无 MVC 集成)
[HttpPost]
public ActionResult Iniciar(Caso c)
{
CasoValidator validator = new CasoValidator();
FluentValidation.Results.ValidationResult validate = validator.Validate(c, ruleSet: "Iniciar");
// ...
}
通过此实现,主类的属性得到了很好的验证,但我还需要验证集合中“Medicamento”类的每个属性。
我可能在这里遗漏了一些东西吗?是否应该使用可用的 RuleForEach 子句进行验证?
任何帮助将不胜感激。