如何替换标准 DataAnnotations 错误消息

发布于 2024-08-19 12:07:50 字数 134 浏览 4 评论 0原文

我正在使用 System.ComponontModel.DataAnnotations 来验证我的模型对象。如何替换消息标准属性(Required 和 StringLength)生成的而不向每个属性提供 ErrorMessage 属性或对它们进行子类化?

I'm using System.ComponontModel.DataAnnotations to validate my model objects. How could I replace messages standard attributes (Required and StringLength) produce without providing ErrorMessage attribute to each of them or sub classing them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不寐倦长更 2024-08-26 12:07:50

写新帖子是因为我需要比评论提供的更多格式。

查看 ValidationAttribute - 验证属性的基类。

如果发生验证错误,将通过方法创建错误消息:

public virtual string FormatErrorMessage(string name)
{
    return string.Format(CultureInfo.CurrentCulture, this.ErrorMessageString, new object[] { name });
}

接下来查看 ErrorMessageString 属性:

protected string ErrorMessageString
{
    get
    {
        if (this._resourceModeAccessorIncomplete)
        {
            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, DataAnnotationsResources.ValidationAttribute_NeedBothResourceTypeAndResourceName, new object[0]));
        }
        return this.ResourceAccessor();
    }
}

属性 ResourceAccessor 可以设置为:

ValidationAttribute..ctor(Func<String>)
ValidationAttribute.set_ErrorMessage(String) : Void
ValidationAttribute.SetResourceAccessorByPropertyLookup() : Void

首先,它完全由派生类使用格式消息,第二个 - 当我们通过 ErrorMessage 属性设置错误消息时的情况,第三个 - 当使用资源字符串时。
根据您的情况,您可以使用ErrorMessageResourceName

在其他地方,让我们看一下派生构造函数,例如 Range 属性:

private RangeAttribute()
    : base((Func<string>) (() => DataAnnotationsResources.RangeAttribute_ValidationError))
{
}

这里 RangeAttribute_ValidationError 是从资源加载的:

internal static string RangeAttribute_ValidationError
{
    get
    {
        return ResourceManager.GetString("RangeAttribute_ValidationError", resourceCulture);
    }
}

因此您可以为不同的 tan 默认区域性创建资源文件并覆盖那里的消息,如下所示:

http://www.codeproject.com/KB/aspnet/SatelliteAssemblies.aspx

http://msdn.microsoft.com/en-us/library /aa645513(VS.71).aspx

Writing new post because I need more formatting than comments provide.

Look at ValidationAttribute - base class of validation attributes.

If validation error occured, error message will be created by method:

public virtual string FormatErrorMessage(string name)
{
    return string.Format(CultureInfo.CurrentCulture, this.ErrorMessageString, new object[] { name });
}

Next look at ErrorMessageString property:

protected string ErrorMessageString
{
    get
    {
        if (this._resourceModeAccessorIncomplete)
        {
            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, DataAnnotationsResources.ValidationAttribute_NeedBothResourceTypeAndResourceName, new object[0]));
        }
        return this.ResourceAccessor();
    }
}

Property ResourceAccessor can be setted from:

ValidationAttribute..ctor(Func<String>)
ValidationAttribute.set_ErrorMessage(String) : Void
ValidationAttribute.SetResourceAccessorByPropertyLookup() : Void

First of it is exactly used by dervided classes to format messages, second - the case when we set error message trough ErrorMessage property, and third - when resource strings used.
Depending on your situation, you may use ErrorMessageResourceName.

Elsewhere let's look at derived constructors, for our example, Range Attribute:

private RangeAttribute()
    : base((Func<string>) (() => DataAnnotationsResources.RangeAttribute_ValidationError))
{
}

Here RangeAttribute_ValidationError is loaded from resource:

internal static string RangeAttribute_ValidationError
{
    get
    {
        return ResourceManager.GetString("RangeAttribute_ValidationError", resourceCulture);
    }
}

So you can create resource file for different tan default culture and overwrite messages there, like this:

http://www.codeproject.com/KB/aspnet/SatelliteAssemblies.aspx

http://msdn.microsoft.com/en-us/library/aa645513(VS.71).aspx

我早已燃尽 2024-08-26 12:07:50

您可以对所有 DataAnnotations 验证器使用基类 ValidationAttributeErrorMessage 属性。

例如:

[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}")]
public int id;

也许会有帮助。

You can use ErrorMessage property of base class ValidationAttribute for all DataAnnotations validators.

For example:

[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}")]
public int id;

Maybe it'll help.

太阳男子 2024-08-26 12:07:50

对于ASP.NET Core验证,请参阅页面,其中解释了如何使用服务引擎进行设置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });
}

否则(WPF、WinForms 或 .NET Framework),您可以使用反射来干扰 DataAnnotations 资源并将其替换为您自己的资源,然后这些资源可以自动依赖于您应用程序当前的区域性。
有关更多信息,请参阅答案:

void InitializeDataAnnotationsCulture()
{
  var sr = 
    typeof(ValidationAttribute)
      .Assembly
      .DefinedTypes
      //ensure class name according to current .NET you're using
      .Single(t => t.FullName == "System.SR");

  var resourceManager = 
    sr
      .DeclaredFields
      //ensure field name
      .Single(f => f.IsStatic && f.Name == "s_resourceManager");

  resourceManager
    .SetValue(null, 
      DataAnnotationsResources.ResourceManager, /* The generated RESX class in my proj */
      BindingFlags.NonPublic | BindingFlags.Static, null, null);

  var injected = resourceManager.GetValue(null) == DataAnnotationsResources.ResourceManager;
  Debug.Assert(injected);
}

For ASP.NET Core validation, refer to this page, where it explains how to set it up using the service engine:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });
}

Otherwise (WPF, WinForms or .NET Framework), you can use reflection to interfere with the DataAnnotations resources and replace them with your own, which can then be automatically culture-dependent on your app's current culture.
Refer to this answer for more:

void InitializeDataAnnotationsCulture()
{
  var sr = 
    typeof(ValidationAttribute)
      .Assembly
      .DefinedTypes
      //ensure class name according to current .NET you're using
      .Single(t => t.FullName == "System.SR");

  var resourceManager = 
    sr
      .DeclaredFields
      //ensure field name
      .Single(f => f.IsStatic && f.Name == "s_resourceManager");

  resourceManager
    .SetValue(null, 
      DataAnnotationsResources.ResourceManager, /* The generated RESX class in my proj */
      BindingFlags.NonPublic | BindingFlags.Static, null, null);

  var injected = resourceManager.GetValue(null) == DataAnnotationsResources.ResourceManager;
  Debug.Assert(injected);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文