如何替换标准 DataAnnotations 错误消息
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
写新帖子是因为我需要比评论提供的更多格式。
查看 ValidationAttribute - 验证属性的基类。
如果发生验证错误,将通过方法创建错误消息:
接下来查看 ErrorMessageString 属性:
属性 ResourceAccessor 可以设置为:
首先,它完全由派生类使用格式消息,第二个 - 当我们通过 ErrorMessage 属性设置错误消息时的情况,第三个 - 当使用资源字符串时。
根据您的情况,您可以使用ErrorMessageResourceName。
在其他地方,让我们看一下派生构造函数,例如 Range 属性:
这里 RangeAttribute_ValidationError 是从资源加载的:
因此您可以为不同的 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:
Next look at ErrorMessageString property:
Property ResourceAccessor can be setted from:
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:
Here RangeAttribute_ValidationError is loaded from resource:
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
您可以对所有 DataAnnotations 验证器使用基类 ValidationAttribute 的 ErrorMessage 属性。
例如:
也许会有帮助。
You can use ErrorMessage property of base class ValidationAttribute for all DataAnnotations validators.
For example:
Maybe it'll help.
对于ASP.NET Core验证,请参阅此页面,其中解释了如何使用服务引擎进行设置:
否则(WPF、WinForms 或 .NET Framework),您可以使用反射来干扰 DataAnnotations 资源并将其替换为您自己的资源,然后这些资源可以自动依赖于您应用程序当前的区域性。
有关更多信息,请参阅此答案:
For ASP.NET Core validation, refer to this page, where it explains how to set it up using the service engine:
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: