21

I have this DateTime attribute in my model:

[Required(ErrorMessage = "Expiration Date is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[DisplayName("Expiration Date")]
public DateTime? ExpirationDate { get; set; }

I'd like this attribute to be validated so that the user can't enter a date that occurred before today. If I was validating an integer, I could do this.

[Range(1, int.MaxValue, ErrorMessage = "Value must be greater than 0")]

But the range attribute doesn't support a DateTime object. Is there something like this for a DateTime value?

Steven
  • 18,761
  • 70
  • 194
  • 296
  • possible duplicate: http://stackoverflow.com/questions/1406046/data-annotation-ranges-of-dates – M.Babcock Jan 13 '12 at 01:24
  • Or maybe one of the answers from this related question: http://stackoverflow.com/questions/5390403/datetime-date-and-hour-validation-with-data-annotation – M.Babcock Jan 13 '12 at 01:26
  • I'm not 100% sure that this relates but maybe the MSDN DateTimeRangeValidator: http://msdn.microsoft.com/en-us/library/ff649440.aspx – M.Babcock Jan 13 '12 at 01:29

1 Answers1

49

This should help you.

public class MyDateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)// Return a boolean value: true == IsValid, false != IsValid
    {
        DateTime d = Convert.ToDateTime(value);
        return d >= DateTime.Now; //Dates Greater than or equal to today are valid (true)

    }
}

Now apply this attribute to your Model property.

    public class SomeModel
    {
       [Display(Name = "Date of birth")]
       [MyDate(ErrorMessage ="Invalid date")]
       public DateTime DateOfBirth { get; set; }
    } 
Parminder
  • 3,088
  • 6
  • 37
  • 61