我正在使用带有 Fluent Validation 的 ASP.NET MVC 3。我希望我的所有错误消息的措辞和格式都相同,无论它们是验证错误消息还是模型绑定(bind)错误消息。
假设我有以下 View 模型:
[Validator(typeof(PersonValidator))]
public class Person
{
[ScaffoldColumn(false)] public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
要使用 Fluent Validation 验证这一点,我可能会使用如下内容:
public class EditorValidator : AbstractValidator<EditorModel>
{
public EditorValidator()
{
RuleFor(model => model.Month.Value).InclusiveBetween(0, 120)
}
}
如果用户为
Age
输入“abc” ,这会导致模型绑定(bind)错误,而不是验证错误。这是因为 "abc"不是 int
.系统甚至不会询问“abc”是否在 0 和 120 之间,因为“abc”不能存储在 Age
中。 .这很好,也很有意义。问题是生成的错误消息是:
The field Age must be a number.
我希望消息的格式和措辞与 Fluent Validation 产生的其他错误消息一样。在这种情况下,我想:
'Age' must be a number.
我意识到这只是一个细微的区别,但我想控制模型绑定(bind)错误消息。
如何自定义模型绑定(bind)错误消息以匹配 Fluent Validation 使用的错误消息?
最佳答案
我不确定是否有其他方法可以做到这一点,但我使用 Data Annotations Extensions ,也可以通过 NuGet (Install-Package DataAnnotationsExtensions.MVC3) 获得这种确切类型的东西。这个包裹会给你一个IntegerAttribute
,然后您可以从那里指定一条错误消息,如下所示:
[Integer(ErrorMessage = "'Age' must be a number.")]
public int Age { get; set; }
关于asp.net-mvc - 在 ASP.NET MVC 3 中自定义模型绑定(bind)错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6488124/