DataTypeAttribute is showing the wrong message

懵懂的女人 提交于 2019-12-23 01:28:33

问题


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



来源:https://stackoverflow.com/questions/10028384/datatypeattribute-is-showing-the-wrong-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!