使用数据注解模型验证错误消息 [英] Error messages for model validation using data annotations

查看:157
本文介绍了使用数据注解模型验证错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于后续类:

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留言联系的每个实例?例如,如果名称是从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.

推荐答案

这是我所知道的唯一的方式,但它从干净远远。它涉及到使用子类和元数据类覆盖的错误消息。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆