[英]FluentValidation how to validate grandchild
Below is my 3 level class (Employee > Project > Teammate).下面是我的 3 级课程(员工 > 项目 > 队友)。 I was able to validate the Status of the child (Project) wherein validate only if the list of projects is not empty.我能够验证子项(项目)的状态,其中仅当项目列表不为空时才进行验证。
However on the Teammate level, I dont know how to check for the TeamateName property.但是在队友级别,我不知道如何检查 TeamateName 属性。 Basically I wanted to do the same on the grandchild, if there are Teammates make sure to check the teammateName if empty or null.基本上我想对孙子做同样的事情,如果有队友,请确保检查 teammateName 是否为空或为空。
Thanks!谢谢!
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public List<ProjectsDto> Projects { get; set; }
}
public class ProjectsDto
{
public string Status { get; set; }
public List<TeammatesDto> Teammates { get; set; }
}
public class TeammatesDto
{
public string TeammateName { get; set; }
public string PreviousProject { get; set; }
}
public class CreateEmployeeCommandValidator : AbstractValidator<CreateEmployeeCommand>
{
private readonly IApplicationDbContext _context;
public CreateEmployeeCommandValidator(IApplicationDbContext context)
{
_context = context;
RuleFor(v => v.Name)
.NotEmpty().WithMessage("Name is required.")
.MaximumLength(30).WithMessage("Name must not exceed 30 characters.");
RuleFor(v => v.Projects)
.ForEach(projectRule => {
projectRule.Must(item => item.Status == null).WithMessage("Status is required");
})
.When(v => !StringUtil.IsNullOrEmptyList(v.Projects));
}
The best and more organized option i think is the use of SetValidator , you can use in a foreach rule, or just for child objects, so the code would be like this:我认为最好和更有条理的选项是使用SetValidator ,您可以在 foreach 规则中使用,或者仅用于子对象,因此代码如下:
RuleFor(v => v.Name)
.NotEmpty()
.WithMessage("Name is required.")
.MaximumLength(30)
.WithMessage("Name must not exceed 30 characters.");
RuleForEach(v => v.Projects)
.SetValidator(new YourProjectsValidator());
And inside YourProjectsValidator you will have the call to the Teammates validator like this:在 YourProjectsValidator 中,您将像这样调用 Teammates 验证器:
RuleForEach(v => v.Teammates)
.SetValidator(new YourTeammatesValidator());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.