Hi everybody,
Suppose I want to add a condition for my date to be greater than today's date. I can implement the logic in the class itself like this
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((EndDate==null) || (StartDate == null))
{
yield return new ValidationResult("StartDate or EndDate is null - something went terribly wrong!");
}
if (EndDate < StartDate)
{
yield return new ValidationResult("Class cannot end before it starts");
}
if (StartDate < DateTime.Now.Date)
{
yield return new ValidationResult("Start Date can not be in the past");
}
if (EndDate > StartDate.Value.AddMonths(1))
{
yield return new ValidationResult("You can not have a class longer than a month");
}
}
However, I see a few problems with this approach.
1. I'd like to have my validation rule a bit separate from the class itself - in a different file, may be? What is the general practice here, how such files are named and where do we put them?
2. I think it may be a better to create as custom data annotations attribute, say, FutureDatesOnly (I have similar propety in my VFP application).
Again, the question is - where do we create such custom attributes in the Objects project? Also, I assume most of such attributes are already developed by someone else - how can I know which attributes are already exist and how can I grab them?
Thanks in advance.
--------
Update. Reading this interesting blog now
http://weblogs.asp.net/srkirkland/archive/2011/02/15/adding-client-validation-to-dataannotations-datatype-attribute.aspx although it looks too complex. I need something simpler.
If it's not broken, fix it until it is.
My Blog