DateRange MVC3 Unobtrusive Client-side Validation do not work

Oct 18, 2011 at 11:39 PM
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:

 

[MetadataType(typeof(FoodMetaData))]
    public partial class FOOD
    {
        [Bind(Exclude = "FoodID")]
        public class FoodMetaData
        {
            [ScaffoldColumn(false)]
            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; }

            
        }
 
[MileStone]
        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>
    <div class="editor-field">
        @Html.DateTimeFor(model => model.ExpiryDate, new { @class = "expirydate" })
        @Html.ValidationMessageFor(model => model.ExpiryDate)
    </div>

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..

 

 

Coordinator
Oct 19, 2011 at 4: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)

Coordinator
Oct 19, 2011 at 5: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