I create the following attribute:
public class SpecificDataTypeAttribute : DataTypeAttribute
{
public SpecificDataType(DataType dataType, string field)
: base(dataType)
{
this.ErrorMessage = string.Format("{0} {1}", field, Messages.SpecificDataTypeAttribute);
}
}
And use like:
[SpecificDataType(DataType.DateTime, "Initial date")]
public DateTime? InitialDate { get; set; }
So, the message that is in Messages.SpecificDataTypeAttribute is "is in a incorrect format.". When i input a wrong date in InitialDate, i got the default error: "The value '12' is not valid for InitialDate.". Why? I put the breakpoint and the code is calling the SpecificDataType ctor.
You are going in wrong direction – in asp.net mvc,
DataTypeAttributedoes not define validation rules. It is more or less like UIHintAttribute – helps to specify which template to use when rendering property in edit or display modes.Take a look at this answer to learn about customizing validation messages for system types
The value for
PropertyValueInvalidis formatted, with {0} replaced by invalid value, and {1} with property name. So you can define it as