I’m developing an application where I use DataAnnotations
to validate the values passed to the class properties. As I have several different classes with many properties that have similar validation rules, I would like to define for the ErrorMessage
argument a method that returns a formatted string. The problem is that when I use this method in the validation attribute I get the following error:
“An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type PrototypeValidationData”
Reading this post I understood that the attribute doesn’t support a method as argument, but I would like to know if there is any way of preventing to repeat the same error message in all the properties definitions. Is there any alternative?
Follows an example of what I’m trying to do:
public class Foo
{
public string Id { get; set; }
[Range(double.Epsilon, double.MaxValue, ErrorMessage = ErrorMessages.MustBeGreaterThanZero(Bar.ToString(), "Foo", Id, "Bar"))]
public double Bar { get; set; }
}
public static class ErrorMessages
{
public static string MustBeGreaterThanZero(string str,
string senderClass,
string senderId,
string senderField)
{
return String.Format("The value {0} assigned to the field {1} in {2} ID {3} must be greater than ZERO.",
str, senderField, senderClass, senderId);
}