在我的验证员课程中,我有几条规则 我需要在数据库中记录一些验证错误。
以下是我的验证人:
RuleFor(u => u.LastName)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("Last name is required")
.Length(3, 20).WithMessage("Must have between 3 and 20 letters");
RuleFor(u => u.BirthDate)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull().WithMessage("Birth date is required")
.Must(c => c > new DateTime(1920, 01, 01)).WithMessage("Too old");
RuleFor(u => u.Age)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull().WithMessage("This is required")
.GreaterThan(18).WithMessage("Must be at least 18")
.Must((model, age, context) =>
{
DateTime today = DateTime.Today;
int ageToCompare = today.Year - model.BirthDate.Year;
return ageToCompare == age;
}).WithMessage("Invalid age");
对于上述规则,我只想记录特定的错误消息。 我知道我可以像这样使用OnAnyFailure:
RuleFor(u => u.Age)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull().WithMessage("This is required")
.GreaterThan(18).WithMessage("Must be at least 18").OnAnyFailure(LogOnFailure)
.Must((model, age, context) =>
{
DateTime today = DateTime.Today;
int ageToCompare = today.Year - model.BirthDate.Year;
return ageToCompare == age;
}).WithMessage("Invalid age").OnAnyFailure(LogOnFailure)
private void LogOnFailure(CreateAccountBindingModel obj))
{
Debug.WriteLine(obj);
}
但这样我就无法记录任何有用的内容,因为OnAnyFailure
将BindingModel作为参数,因此我只会获取用户输入的值而不会显示错误消息。
我尝试创建可用作OnAnyFailure
的扩展方法,但由于我是FluentValidation的新手,我甚至无法编译我的代码。
以下是我的代码:
public static class IRuleBuilderOptionsExtensions
{
public static IRuleBuilderOptions<T, TProperty> OnAnyFailure<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<T, PropertyValidatorContext> onFailure)
{
return rule;
//return rule.Configure(config => {
// config.OnFailure = onFailure.CoerceToNonGeneric();
//});
}
}
这样我就可以打电话:
private void LogOnFailure(CreateAccountBindingModel obj), PropertyValidatorContext context)
{
//log logic
}
基本上我需要的是为LogOnFailure
创建能够访问PropertyValidatorContext的覆盖。
答案 0 :(得分:0)
您可以第二次验证您的模型以显示它:
background: url(../media/pic.png) no-repeat center center fixed;