This project is read-only.

DateRange MVC3 Unobtrusive Client-side Validation do not work

Oct 19, 2011 at 12:39 AM
Hi, this is my first time using MVC Controls Toolkit and I cant really understand how to use it. I need to have a custom validation of a Date field so I declare a partial class in my Model like this:


    public partial class FOOD
        [Bind(Exclude = "FoodID")]
        public class FoodMetaData
            public int FoodID { get; set; }
            public object StorageDate { get; set; }

            [DateRange(DynamicMinimum="Today", ErrorMessage="Test")]
            [DateRange(DynamicMinimum="StorageDate", ErrorMessage="Test storage date")]
            public DateTime? ExpiryDate { get; set; }

        public DateTime Today
            get { return DateTime.Now; }
            set { }


I got ExpiryDate and Storagedate, where Expirydate should be later or equal to today's date. Also, the Expirydate should not be earlier than the StorageDate.

However, I got no idea how to implement the validation and my trial seems failed. I get compilation error at the form html when i try to use DateTimeFor:

<div class="editor-label">
        Expiry Date
    <div class="editor-field">
        @Html.DateTimeFor(model => model.ExpiryDate, new { @class = "expirydate" })
        @Html.ValidationMessageFor(model => model.ExpiryDate)

It says cannot implicitly convert datetime? to datetime. So how should I explicitly cast it?

Also, If i use html.editorfor for the datetime field, the validation just dint work. Validation at other field in the same form work..

Please help.. I googled a lot yet still cant find a working solution.. Really really appreciate that..



Oct 19, 2011 at 5:53 PM

I answered you in the Mvc forum :). 


Here just repeat DateTimeFor doesn0t return Html to put in the view but another object that you can use to render separate date and separate time (if you want)

Oct 19, 2011 at 6:04 PM

Please Note also I assumed you render also StorageDate in the page(with a DateTimeInput also).

If you don't render it in the page you have to put the Milestone attribute on it as you have done for the Today property