【问题标题】:FluentValidation - How to customize the validation message in runtimeFluentValidation - 如何在运行时自定义验证消息
【发布时间】:2015-06-11 02:22:57
【问题描述】:

在这个实体中:

public class Foo
{
    public Guid Id { get; set; }
    public string Type { get; set; }
    public string Name { get; set; }
}

如何使用实体的另一个属性或从数据库中获取的任何其他字符串在运行时自定义验证消息?

RuleFor(foo => foo.Name) 的验证消息是:

var msg = "The foo with type '" + foo.Type + "' already exists in the database with name '" + nameInDataBase + "'!"

【问题讨论】:

标签: c# validation message fluentvalidation


【解决方案1】:

由于我有一个复杂的场景,解决我的问题的解决方案在这里找到:Custom Validators

这是验证器代码:

public class FooValidator : AbstractValidator<Foo>
{
    public FooValidator()
    {
        Custom(foo =>
        {
            var repo = new Repository<Foo>();
            var otherFooFromDB = repo.GetByName(foo.Name);

            if (!otherFooFromDB.Equals(foo))
            {
                return new ValidationFailure("Id", "The foo with ID'" + otherFooFromDB.Id + "' has the same name of this new item '" + foo.Id + " - " + foo.Name + "'.!");
            }
            else
            {
                return null;
            }
        });
    }
}

如果验证正常,使用此解决方案只需返回 null。 但是当出现验证错误时,返回一个ValidationFailure 的实例并在她的构造函数中传递经过验证的属性的名称和验证消息。

【讨论】:

  • 我会对上面的内容做一个改变,就是将你的 repo 注入验证器,否则你会让测试变得很痛苦。
  • 是的@YannickMeeus!! ...我将Interface 用于我的存储库以使测试成为可能...使用模拟。
【解决方案2】:

创建几个自定义验证器,并将它们定义为扩展方法,以便您可以链接它们。将验证所需的内容传递到模型中。然后,如果您将 foo.Type 作为模型的属性,则可以在消息中显示它,如下所示:

RuleFor(foo => foo.Name).FooTypeIsInvalidValidator().WithMessage("The foo with type: {0} is invalid!", foo => foo.Type);

RuleFor(foo => foo.Name).FooAlreadyExistsValidator().WithMessage("The foo with type: {0} already exists in the database with name", foo => foo.Type);

【讨论】:

  • 谢谢 KN Coder (@kn-coder),但我的情况更复杂。我发布了新的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 2013-09-03
  • 2019-03-21
  • 2011-12-28
  • 2014-05-31
相关资源
最近更新 更多