gpt4 book ai didi

c# - Fluent Validation,在 Asp.NET Core 中对列表中的每个项目进行不同的验证

转载 作者:行者123 更新时间:2023-11-30 20:29:19 26 4
gpt4 key购买 nike

我一直在尝试寻找一种方法来验证列表中的项目,每个项目都有不同的验证规则。我遇到了 Fluent validation,这是一个很棒的库,但我似乎无法找到一种方法来单独对每个项目进行验证。我从这个类似的线程 ( Validate 2 list using fluent validation ) 中得到了一个模糊的想法,但我不确定如何按照我想要的方式关注它。

所以我有这个 View 模型:

 public class EditPersonalInfoViewModel
{
public IList<Property> UserPropertyList { get; set; }
}

这包含一个 Active Directory 属性列表。每个都由这个类代表:

   public class Property
{
public string Name { get; set; }
public UserProperties Value { get; set; }
public string input { get; set; }
public bool Unmodifiable { get; set; }
public string Type { get; set; }
}

重点是,每个 AD 属性都有不同的约束,所以我想以某种方式为列表中的每个属性指定不同的规则,如下所示:

   public class ADPropertiesValidator : AbstractValidator<EditPersonalInfoViewModel>
{
public ADPropertiesValidator()
{
RuleFor(p => p.UserPropetyList).Must((p,n) =>
{
for (int i = 0; i < n.Count; i++)
{
if ((n[i].Name.Equals("sAMAccountName"))
{
RuleFor(n.input ).NotEmpty()....
}
else if(...)
{
//More Rules
}
}
)

}
}

有什么想法可以解决这个问题吗?提前致谢。

最佳答案

您从错误的角度进行验证。无需在您的集合容器类中创建验证条件,只需创建另一个特定于您的 Property 类的验证器,然后在您的 ADPropertiesValidator 中使用它:

public class ADPropertyValidator : AbstractValidator<Property>
{
public ADPropertyValidator()
{
When(p => p.Name.Equals("sAMAccountName"), () =>
{
RuleFor(p => p.input)
.NotEmpty()
.MyOtherValidationRule();
});

When(p => p.Name.Equals("anotherName"), () =>
{
RuleFor(p => p.input)
.NotEmpty()
.HereItIsAnotherValidationRule();
});
}
}

public class ADPropertiesValidator : AbstractValidator<EditPersonalInfoViewModel>
{
public ADPropertiesValidator()
{
RuleForEach(vm => vm.UserPropertyList)
.SetValidator(new ADPropertyValidator());
}
}

关于c# - Fluent Validation,在 Asp.NET Core 中对列表中的每个项目进行不同的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46285434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com