在这个实体中:
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/