如何在c#中实现全局必需的错误消息?

时间:2017-01-27 04:54:25

标签: c#

这是我的代码:

[Required(ErrorMessage = "This Field is Required")]
public string FirstName{ get; set; }

不是在每个属性上面写(ErrorMessage = "This Field is Required"),而是可以在全局设置ErrorMessage吗?

1 个答案:

答案 0 :(得分:4)

要在所有给定的必需属性中设置自定义错误消息而不对每个属性使用ErrorMessage,请创建一个派生自System.ComponentModel.DataAnnotations.RequiredAttribute的属性类,并在构造函数部分中设置默认验证消息,如下所示(信用到<强烈> Chad Yeates 的建议):

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class CustomRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, IClientValidatable
{
    public CustomRequiredAttribute()
    {
        this.ErrorMessage = "This Field is Required"; // custom error message here
    }

    public override bool IsValid(object value)
    {
        return base.IsValid(value);
    }

    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(name); // expandable to format given message later
    }
}

用法:

[CustomRequired]
public string FirstName { get; set; }

类似问题:

MVC: Override default ValidationMessage

how to put DisplayName on ErrorMessage format