问题描述
我有一个旧的C#MVC 2.0 Web应用程序.
I have an old C# MVC 2.0 web application.
每当我使用[Required]
属性时,默认的验证错误消息就会出现:
Whenever I use a [Required]
attribute, the default validation error message goes:
我的问题是应用程序不是英语的,所以我基本上必须在任何地方将属性调用更改为[Required(ErrorMessage = "Le champ [whatever] est requis.")]
.
My problem is that the application isn't in English, so I basically have to change the attribute call to [Required(ErrorMessage = "Le champ [whatever] est requis.")]
everywhere.
是否有一种方法可以覆盖默认错误消息,因此仅在需要特定消息时才需要指定它?
Is there a way to override the default error message so I only have to specify it when I want a specific message?
我正在寻找类似的东西:
I'm looking for something like:
DefaultRequiredMessage = "Le champ {0} est requis.";
推荐答案
您可以创建一个类,并从 RequiredAttribute
.像这样:
You can create a class and inherit it from RequiredAttribute
. Something like this:
public class CustomRequired: RequiredAttribute
{
public CustomRequired()
{
this.ErrorMessage = "Le champ est requis.";
}
}
或者:
public class CustomRequired: RequiredAttribute
{
public override string FormatErrorMessage(string whatever)
{
return !String.IsNullOrEmpty(ErrorMessage)
? ErrorMessage
: $"Le champ {whatever} est requis.";
}
}
您应该将CustomRequired
与属性一起使用,而不是[Required]
.
You should use CustomRequired
with your properties, rather than [Required]
.
这篇关于如何覆盖默认的必需错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!