views:

81

answers:

2

I'll be tackling writing a custom date validation class tomorrow for a meeting app i'm working on at work that will validate if a given start or end date is A) less than the current date, or B) the start date is greater than the end date of the meeting (or vice versa).

I think this is probably a fairly common requirement. Can anyone point me in the direction of a blog post that might help me out in tackling this problem?

I'm using .net 3.5 so i can't use the new model validator api built into .NET 4. THe project i'm working on is MVC 2.

UPDATE: THe class i'm writing needs to extend the System.ComponentModel.DataAnnotations namespace. In .NET 4 there is a IValidateObject interface that you can implement, that makes this sort of thing an absolute doddle, but sadly i can't use .Net 4. How do i go about doing the same thing in .Net 3.5?

+1  A: 

I think this should do it:

public boolean MeetingIsValid( DateTime start, DateTime end )
{
      if( start < DateTime.Now || end < DateTime.Now )
          return false;

      return start > end || end < start;
}
jfar
Hi thanks, after reading you answer i realised i needed to provide my info. Of course the code that you have provided will validate a date, but it wasn't that part of the problem i was stuck on. I needed to know what interfaces to implement to extend the dataannotations namespace. Thanks anyway.
Doozer1979
+1  A: 
public sealed class DateStartAttribute : ValidationAttribute
    {        
        public override bool IsValid(object value)
        {
            DateTime dateStart = (DateTime)value;
            // Cannot shedule meeting back in the past.
            return (dateStart < DateTime.Now);
        }
    }

    public sealed class DateEndAttribute : ValidationAttribute
    {
        public string DateStartProperty { get; set; }
        public override bool IsValid(object value)
        {
            // Get Value of the DateStart property
            string dateStartString = HttpContext.Current.Request[DateStartProperty];
            DateTime dateEnd = (DateTime)value;
            DateTime dateStart = DateTime.Parse(dateStartString);

            // Meeting start time must be before the end time
            return dateStart < dateEnd;
        }
    }

and in your View Model:

[DateStart]
public DateTime StartDate{ get; set; }

[DateEnd(DateStartPropertyName="StartDate")]
public DateTime EndDate{ get; set; }

In your action, just check that ModelState.IsValid. That what you're after?

just.jimmy
Does look pretty good, I can't test it at the moment, but i'll be able to do it by the end of the day. Thanks!
Doozer1979
In this case how do i pick up the values for StartDate and EndDate from the model, since they are both user entered values?
Doozer1979
Changed my answer. :) So StartDate checks with DateTime.Now. EndDate checks with StartDate which is user entered to make sure it's after the start date.
just.jimmy
Works like a charm. Thanks!
Doozer1979