【问题标题】:How to override default required error message如何覆盖默认所需的错误消息
【发布时间】:2018-10-29 09:12:09
【问题描述】:

我有一个旧的 C# MVC 2.0 Web 应用程序。

每当我使用[Required] 属性时,默认的验证错误消息都会显示:

[whatever] 字段是必需的。

我的问题是应用程序不是英文的,所以我基本上必须将属性调用更改为[Required(ErrorMessage = "Le champ [whatever] est requis.")]

有没有办法覆盖默认错误消息,所以我只需要在需要特定消息时指定它?

我正在寻找类似的东西:

DefaultRequiredMessage = "Le champ {0} est requis.";

【问题讨论】:

  • 我没听明白,[Required(ErrorMessage = "MyNotEnglishMessage")] 有什么问题?
  • 我不想在我的应用程序中到处写相同的消息,我想遵循 DRY 原则
  • 您能不能只安装法语语言包并将 CurrentUICulture 设置为法国文化(例如 fr 或 fr-FR)?或者,如果您不想安装语言包,请使用自定义资源管理器:stackoverflow.com/questions/2347650/…
  • @Joe 这是一个很老的应用程序,所以我什至不知道我是否能找到法语语言包,我真的不想冒险搞砸一切与所需的不完全匹配。我认为 S.Akbari 的解决方案接近您的第二个选择,所以我宁愿看看这是否按预期工作,因为它几乎没有机会搞砸事情。但是,我同意拥有法语语言包将是一个很好的解决方案!

标签: c# asp.net-mvc asp.net-mvc-2 data-annotations


【解决方案1】:

您可以创建一个类并从RequiredAttribute 继承它。像这样的:

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]

【讨论】:

  • 如何更改它以在错误消息中包含字段名称?
  • 不应该是CustomRequiredAttribute而不是CustomRequired吗?无论如何,谢谢你,让我试试看,如果它按预期工作,我会接受这个答案
  • @Rafalon 这只是您的自定义类的名称。随意将其命名为您喜欢的任何名称:)
  • 是的,我只是认为它应该以Attribute 结尾,所以我们可以使用[CustomRequired]
【解决方案2】:

请执行以下操作以覆盖默认所需的错误消息:

  • 创建一个继承RequiredAttributeAdapter的自定义适配器,如下所示:

public class YourRequiredAttributeAdapter : DataAnnotationsModelValidator<RequiredAttribute>
{
    public YourRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
        if (string.IsNullOrWhiteSpace(attribute.ErrorMessage)
            )
        {
            attribute.ErrorMessageResourceType ="Your resource file";
            attribute.ErrorMessageResourceName = "Keep the key name in resource file as "PropertyValueRequired";
        }
    }

}
  • 在 Global.asax Application_Start() 中注册适配器,如下所示:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(YourRequiredAttributeAdapter));

  • 资源文件配置:

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 2011-02-25
    • 2011-06-22
    • 2023-03-31
    • 1970-01-01
    • 2010-12-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多