ASP.NET MVC Date Validation

I had the following property in my view model:

        [Required(ErrorMessage = "Du måste fylla i från-datum och -tid")]
        public DateTime? From { get; set; }

When I entered “2014-01-01 00:00:00” I got the following validation error: “The field From must be a date.” So, it the built in validation somehow assumes a date without time.

My next attempt was to add a another attribute:

        [DataType(DataType.DateTime)]

This had no effect. My third attempt was to use a regular expression. I defined a new attribute that inherits RegularExpressionAttribute:

    public class DateTimeValidationAttribute : RegularExpressionAttribute
    {
        public DateTimeValidationAttribute()
            : base(@"^((20\d{2})-((0[1-9])|(1[0-2]))-(0[1-9]|1\d|2[0-8])|((20\d{2})-(((0[1,3-9]|1[0-2])-((29|30)))|((0[13578]|1[02])-31)))|(((20(([02468][048])|([13579][26]))))-02-29)) (([0-1]\d)|(2[0-3])):[0-5]\d$")
        {
            ErrorMessage = "Fyll i datum och tid på formatet YYYY-MM-DD HH:mm";
        }
    }

This had no effect either! Still the same validation error. I concluded my validation is not run, maybe because the property is of type DateTime. I changed this to string. This, time I got no client side validation, but at least I got correct server side validation. My last attempt was to skip DataTimeValidationAttribute and use RegularExpressionAttribute directly.

        [Required(ErrorMessage = "Du måste fylla i från-datum och -tid")]
        [DataType(DataType.DateTime)]
        [RegularExpression(DateTimeRegExp, ErrorMessage = DateTimeError)]
        public string From { get; set; }

This was the only solution that worked for me.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s