Reputation: 12764
I would like to replace the default error message for for example RequiredAttribute
or RegularExpressionAttribute
with my own messages, so that I wouldn't need to specify the explicit ErrorMessage
at attribute usage.
EDIT: Last part of the sentence means that I'm aware of the ability to specify my own ErrorMessage
at attribute usage, and I would like to avoid it for keeping the project DRY.
Is it possible somehow? I haven't found any related property in the .NET library, and I currently have no idea how I could replace the .NET resources where the default messages are stored.
Upvotes: 1
Views: 997
Reputation: 6486
Just create your own version of the [Required]
attribute that has a default message that you want. If you only want to use a custom error message have it inherit from RequiredAttribute
so you can take advantage of the same IsValid
logic
public class MyRequired : RequiredAttribute
{
public MyRequired()
{
this.ErrorMessage = "Custom Validation Error Message.";
}
}
If you need even finer control over other validation behaviors, you can create your own DataAnnotation Attributes.
public class MyRequired : ValidationAttribute
{
public MyRequired() : base("My Custom Message")
{
}
public override bool IsValid(object value)
{
//Your custom validation logic
return (value != null);
}
}
Upvotes: 1