I have two date fields: StartDate and EndDate. StartDate must be earlier than EndDate.
If the user changes the StartDate to something greater than the EndDate, a red border appears around that DatePicker, and vise versa. If the user changes the 2nd box so that the date range is now correct, the 1st box still has the Validation Error.
How can I validate both date fields when either one of them changes?
I'm using IDataErrorInfo
public string GetValidationError(string propertyName)
{
switch (propertyName)
{
case "StartDate":
if (StartDate > EndDate)
s = "Start Date cannot be later than End Date";
break;
case "EndDate":
if (StartDate > EndDate)
s = "End Date cannot be earlier than Start Date";
break;
}
return s;
}
I cannot simply raise a PropertyChange event because I need to validate both fields when either of them changes, so having both of them raise a PropertyChange event for the other will get stuck in an infinite loop.
I also do not like the idea of clearing the Date field if the other date returns a validation error.
The simplest way is to raise a
PropertyChanged
notification for in the setter for both properties that need to be validated like bathineni suggestsHowever if that doesn't work for you, I figured out one way to validate a group of properties together, although your classes have to implement
INotifyPropertyChanging
in addition toINotifyPropertyChanged
(I'm using EntityFramework and by default their classes implement both interfaces)Extension Method
To use it, add the following call to the constructor of any class that should validate a group of properties together.
I've tested this with up to 3 properties in a Validation Group and it seems to work OK.
Use this trick, it prevents they call OnPropertyChanged each other :
You can also subscribe to the SelectedDateChanged event handler and update needed binding.
I generally add all of my validation errors to a dictionary, and have the validation template subscribe to that via the property name. In each property changed event handler, I can check any number of properties and add or remove their validation status as necessary.
Check this answer for how my implementation looks. Sorry it is in VB.NET, but should be fairly straightforward.