DataTypeAttribute shows invalid message

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 entered the wrong date in InitialDate, I got a default error: "The value '12' is not valid for InitialDate." . What for? I set a breakpoint and the code calls the SpecificDataType ctor.

+1
source share
2 answers

You are going in the wrong direction - in asp.net mvc, DataTypeAttribute does not define validation rules. This is more or less similar to UIHintAttribute - it helps to specify which template to use when rendering properties in edit or display modes.

See this answer to learn about setting up validation messages for system types.

The value for PropertyValueInvalid formatted with {0} replaced by an invalid value and {1} with the property name. So you can define it as

{1} is in an invalid format

+1
source
0
source

All Articles