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?
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: