c# - FluentValidation - 如何在运行时自定义验证消息

标签 c# validation message fluentvalidation

在这个实体中:

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 + "'!"

最佳答案

由于我遇到了一个复杂的场景,所以在这里找到了解决我问题的解决方案: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 实例,并在她的构造函数中传递经过验证的属性的名称和验证消息。

关于c# - FluentValidation - 如何在运行时自定义验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30770502/

相关文章:

c# - 使用NHibernate时如何处理不同的实体实例?

mysql - MySql密码中的特殊字符

python - 将 postfix 邮件集成到我的(python)webapp

java - thymeleaf : How to use Custom Message Key in JSR-303 Annotation

c# - 如何在 EF Core 中获取数据库表主键列的列表

c# - 覆盖 FloatingActionButton.Behavior 中的方法时 Xamarin Android 名称发生冲突

c# - AutoMapper 2.1.265 中缺少成员

javascript - 加载时 knockout 下拉验证?必需的

ruby-on-rails - Rails 3 : Duplicate validation error messages during testing

message - 如何告诉对象执行消息