Compare Dates DataAnnotations Validation asp.net mvc
Posted
by oliver
on Stack Overflow
See other posts from Stack Overflow
or by oliver
Published on 2010-05-17T11:43:37Z
Indexed on
2010/05/25
1:31 UTC
Read the original article
Hit count: 1044
Lets say I have a StartDate and an EndDate and I wnt to check if the EndDate is not more then 3 months apart from the Start Date
public class DateCompare : ValidationAttribute { public String StartDate { get; set; } public String EndDate { get; set; }
//Constructor to take in the property names that are supposed to be checked
public DateCompare(String startDate, String endDate)
{
StartDate = startDate;
EndDate = endDate;
}
public override bool IsValid(object value)
{
var str = value.ToString();
if (string.IsNullOrEmpty(str))
return true;
DateTime theEndDate = DateTime.ParseExact(EndDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
DateTime theStartDate = DateTime.ParseExact(StartDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).AddMonths(3);
return (DateTime.Compare(theStartDate, theEndDate) > 0);
}
}
and I would like to implement this into my validation
[DateCompare("StartDate", "EndDate", ErrorMessage = "The Deal can only be 3 months long!")]
I know I get an error here... but how can I do this sort of business rule validation in asp.net mvc
© Stack Overflow or respective owner