【问题标题】:fluentvalidation: apply globally for all string propertiesfluentvalidation:全局应用于所有字符串属性
【发布时间】:2021-12-03 15:31:02
【问题描述】:

我想全局验证所有字符串属性,以便它们不以“=”字符开头。

有没有办法使用 FluentValidator 对所有字符串属性进行全局验证。

我已经通过documentation,但我找不到任何方法!

【问题讨论】:

  • 创建Base Class 是我看到的一种解决方法

标签: c# .net-core fluentvalidation


【解决方案1】:

我认为如果存在这样的机会,他们会在文档中提到它,但正如您所见,他们没有。在我看来,添加这样的工具并不是一个好主意,因为在所有具有特定类型的验证器实例之间共享验证规则可能会导致意外的验证结果。这也意味着您必须制作一个可以从全局上下文中排除特定验证器的工具。因此,将编辑单个 .cs 文件与您的具体类型的验证器进行比较,不要害怕破坏其他人的验证逻辑,以使用使您的代码更不可靠、更难以理解和维护的东西。还值得吗?

但是,如果您确定可以在验证器之间共享验证规则,那么您可以使用基类来存储这些规则(正如您在 cmets 中提到的那样)。

例子:

public class Parent
{
    public string ParentValue1 { get; set; }

    public string ParentValue2 { get; set; }
}

public class Child : Parent
{
}  

和验证器:

public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
        RuleFor(x => x.ParentValue1).NotEmpty();
        RuleFor(x => x.ParentValue2).NotEmpty();
    }
}

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        Include(new ParentValidator());
    }
}

【讨论】:

  • 软件中总是有有效的用例,我们为什么需要一些东西。所以仍在尝试寻找一种在全球范围内应用验证的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 2013-05-12
  • 2017-01-17
相关资源
最近更新 更多