1

I need to find the best way to limit my DateTime field to today's date. I need to make sure that users do not select a date in the future and I'm trying to figure out the best way to do it in my C# MVC application.

I could and I will do it on a client side via Javascript. What I'm trying to figure out is the best way to do it on the server side, via DataAnnotations possibly ?

Is there a DataAnnotations attribute I can use to specify max DateTime ? Or is it not a good way to do it through dataannotations because every day my MaxDate will change to its current day ?

Should I do validation just via C# programming logic ?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
InspiredBy
  • 4,271
  • 6
  • 40
  • 67
  • Duplicate: http://stackoverflow.com/questions/1406046/data-annotation-ranges-of-dates – Ivan Zlatev Apr 23 '12 at 17:35
  • It's not. My question is not about static dates. I'm aware of Range dataAnnotations attribute but I'm concerned using DateTime.Now in that attribute is not a good idea. Or is it ok ? Is this acceptable ? [Range(typeof(DateTime), DateTime.Min, DateTime.Now – InspiredBy Apr 23 '12 at 17:43

1 Answers1

2

I've got something similar in one of my apps

 public sealed class DateEndAttribute : ValidationAttribute
{
    public string DateStartProperty { get; set; }
    public override bool IsValid(object value)
    {
        // Get Value of the Date property
        string dateString = HttpContext.Current.Request[YourDateProperty];
        DateTime dateNow = DateTime.Now
        DateTime dateProperty = DateTime.Parse(dateString);

        // 
        return dateProperty < dateNow;
    }
}
MrBliz
  • 5,830
  • 15
  • 57
  • 81
  • Quick question on custom dataAnnotations as I haven't worked with them before. Would it be a good practice to stick the custom validator inside of the Entity model class or should it be kept separately ? – InspiredBy Apr 23 '12 at 17:58
  • I usually store all my custom attributes separately, unless the are specific to that class only. – MrBliz Apr 23 '12 at 18:02
  • Thank you. I combined yours and the following solution: http://stackoverflow.com/questions/5390403/datetime-date-and-hour-validation-with-data-annotation – InspiredBy Apr 23 '12 at 18:57
  • MrBliz, when you get the property, why not use the passed in `value` instead of inspecting the current request for a named property value. That way the attribute could be re-used easily across different properties. – KyleMit Jan 20 '15 at 14:31
  • you need to ensure you take into consideration the culture settings otherwise your DateTime parse will throw an exception if it cannot parse to the correct format passed into the Request. – Ahmed ilyas Jan 20 '15 at 22:42