开发者

MVC validation of Date using DataAnnotations

This is my Model class

public class Model
{
    [DataType(DataType.DateTime, ErrorMessage = "My error message")]
    public DateTime Day { get; set; }
}

When I try to input incorrect value for example "notdate" i got the error "The value 'notdate' is not valid for Day." instead of my specified ErrorMessage "My error message".

I use ASP.开发者_C百科NET MVC 3.0 beta. This is a bug?


There are a few things to note about the behavior you are describing.

First, you are receiving this error because an exception is being thrown when attempting to assign the string value 'notdate' to a DateTime field. When this happens, any validation messages that may have been associated with the field will be overwritten with the generic message: The value '{0}' is not valid for {1}.

Second,the base DataTypeAttribute doesn't actually perform any validation on the field. Using Reflector, you will see that the DataTypeAttribute.IsValid() method is declared as follows:

public override bool IsValid(object value)
{
    return true;
}

Hope this helps.


No, this is the default functionality of the existing model binder.

The DataType has nothing to do with basic model binding and won't override basic model binding errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜