简体   繁体   中英

How do I implement global required error message in c#?

This is my code:

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

Instead of writing (ErrorMessage = "This Field is Required") above every property, can I set the ErrorMessage Globally?

To set customized error message in all given required attributes without using ErrorMessage for each property, create an attribute class which derives from System.ComponentModel.DataAnnotations.RequiredAttribute and set default validation message in constructor part like below (credits to Chad Yeates for his advice):

[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
    }
}

Usage:

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

Similar issues:

MVC: Override default ValidationMessage

how to put DisplayName on ErrorMessage format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM