使用数据注释进行模型验证的错误消息 [英] Error messages for model validation using data annotations
问题描述
给定以下类:
using System.ComponentModel.DataAnnotations;
public class Book{
public Contact PrimaryContact{get; set;}
public Contact SecondaryContact{get; set;}
[Required(ErrorMessage="Book name is required")]
public string Name{get; set;}
}
public class Contact{
[Required(ErrorMessage="Name is required")]
public string Name{get; set;}
}
是否有一种干净的方法可以使用 DataAnnotations
为 Book
中的每个 Contact
实例提供不同的错误消息?例如,如果 PrimaryContact
实例中缺少姓名,则错误将显示为需要主要联系人姓名".
Is there a clean way I can give a distinct error message for each instance of Contact
in Book
using DataAnnotations
? For example, if the name was missing from the PrimaryContact
instance the error would read "primary contact name is required".
我当前的解决方案是创建一个验证服务来检查模型状态是否存在字段错误,然后删除所述错误并使用我喜欢的特定语言将它们添加回来.
My current solution is to create a validation service that checks the model state for field errors, then remove said errors and add them back using the specific language I'd like.
推荐答案
这是我知道的唯一方法,但它远非干净.它涉及使用子类化和 MetaData 类来覆盖"错误消息.
This is the only way I know of that, but it's far from clean. It involves using subclassing and MetaData classes to "override" the error message.
public class Book
{
public PrimaryContact PrimaryContact { get; set; }
public SecondaryContact SecondaryContact { get; set; }
[Required(ErrorMessage = "Book name is required")]
public string Name { get; set; }
}
public class Contact
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
}
[MetadataType(typeof(PrimaryContactMD))]
public class PrimaryContact : Contact
{
class PrimaryContactMD
{
[Required(ErrorMessage = "Primary Contact Name is required")]
public string Name { get; set; }
}
}
[MetadataType(typeof(SecondaryContactMD))]
public class SecondaryContact : Contact
{
class SecondaryContactMD
{
[Required(ErrorMessage = "Secondary Contact Name is required")]
public string Name { get; set; }
}
}
这篇关于使用数据注释进行模型验证的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!