1

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?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Anuj Tamrakar
  • 251
  • 2
  • 13

1 Answers1

4

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

Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61