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?
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With