gpt4 book ai didi

c# - 如何使用 Fluent Validator 在 RuleForEach 验证消息中返回特定属性?

转载 作者:行者123 更新时间:2023-12-05 02:55:59 25 4
gpt4 key购买 nike

假设我有一个这样的测试类:

public class TestClass
{
public Properties[] TestProperties { get; set; }
public Guid Id { get; set; }

public TestClass(Properties[] testProperties)
{
Id = Guid.NewGuid();
TestProperties = testProperties;
}
}

和一个 Properties 类如下:

 public class Properties
{
public Guid Id { get; set; }
public string Name { get; set; }

public Properties(string name)
{
Name = name;
Id = Guid.NewGuid();
}
}

我需要验证 TestProperties 数组中的所有属性 Name 是否为 null,如下所示:

public class TestValidator : AbstractValidator<TestClass>
{
public TestValidator()
{
RuleForEach(x => x.TestProperties)
.Must(y => y.Name != string.Empty && y.Name != null)
.WithMessage("TestPropertie at {CollectionIndex}, can't be null or empty");
}
}

但是我不想返回失败属性的位置,在验证消息中,我想返回它的 Id,我该怎么做呢?

最佳答案

是的,使用默认验证器可以将对象的其他属性值注入(inject)到消息中。

This can be done by using the overload of WithMessage that takes a lambda expression, and then passing the values to string.Format or by using string interpolation.

Source

有几种方法可以做到这一点。首先,根据您当前使用 Must 的实现:

public class TestClassValidator : AbstractValidator<TestClass>
{
public TestClassValidator()
{
RuleForEach(x => x.TestProperties)
.Must(y => !string.IsNullOrEmpty(y.Name))
.WithMessage((testClass, testProperty) => $"TestProperty {testProperty.Id} name can't be null or empty");
}
}

我尽可能避免使用 Must,如果您坚持使用内置验证器,您更有可能开箱即用地进行客户端验证(如果您正在使用它在网络应用程序中)。使用 ChildRules 可以让您使用内置的验证器,还可以获得使用流畅界面的好处:

public class TestClassValidator : AbstractValidator<TestClass>
{
public TestClassValidator()
{
RuleForEach(x => x.TestProperties)
.ChildRules(testProperties =>
{
testProperties.RuleFor(testProperty => testProperty.Name)
.NotNull()
.NotEmpty()
.WithMessage(testProperty => $"TestProperty {testProperty.Id} name can't be null or empty");
});
}
}

ChildRules doco

我已经将 NotNull() 验证器包含在自定义错误消息中,用于验证冗长/对齐,但是不需要它,因为 NotEmpty() 将涵盖 null 或空的情况。

最后,如果是我,我可能会为 Properties 类型创建一个单独的验证器(这应该是 Property 吗?)并使用 SetValidator 包括它。拆分验证问题,一次定义类型的验证并使规则可重用,并使验证器更易于测试。我不打算在这里讨论这个问题,因为这超出了这个问题的范围,但下面的链接给出了如何做的例子。

子验证器 doco(SetValidator 用法)herehere

可以找到上述工作样本,包括测试 here .

关于c# - 如何使用 Fluent Validator 在 RuleForEach 验证消息中返回特定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60893578/

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