DataTypeAttribute is showing the wrong message

2019-06-03 05:19发布

问题:

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.

回答1:

You are going in wrong direction - in asp.net mvc, DataTypeAttribute does 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 PropertyValueInvalid is formatted, with {0} replaced by invalid value, and {1} with property name. So you can define it as

{1} is in invalid format



回答2:

In MVC 4 is possible to localize default error message. http://weblogs.asp.net/imranbaloch/archive/2013/03/31/localizing-default-error-messages-in-asp-net-mvc-and-web-form.aspx