Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict DateTime value with data annotations

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?

like image 360
Steven Avatar asked Jan 13 '12 01:01

Steven


1 Answers

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; }
    } 
like image 57
Parminder Avatar answered Sep 20 '22 16:09

Parminder