Hi,
I'm looking for the best practice for creating a generic data validation
implementation for my data bound business objects. I currently have a
business object base class implementing the following interfaces:
IEditableObject, ICloneable, INotifyPropertyChanged, and IDataErrorInfo
More specifically, my IDataErrorInfo implementation is like so:
[NonSerialized]
private Dictionary<string, string> propertyErrors;
[NonSerialized]
private string classError;
/// <summary>
/// Initializes a new instance of the BusinessObjectBase class
/// </summary>
public BusinessObjectBase()
{
propertyErrors = new Dictionary<string, string>();
}
#region IDataErrorInfo Members
/// <summary>
/// Gets or Sets the error message for the business object
/// </summary>
public string Error
{
get { return classError; }
set { classError = value; }
}
/// <summary>
/// Gets the current error message associated with the specified
property name
/// </summary>
/// <param name="propertyName">The property name</param>
/// <returns>An error message, or string.Empty</returns>
public string this[string propertyName]
{
get
{
if (propertyErrors.ContainsKey(propertyName))
{
return propertyErrors[propertyName];
}
else
{
return string.Empty;
}
}
}
/// <summary>
/// Sets the error message for a property
/// </summary>
/// <param name="propertyName">The property name</param>
/// <param name="error">The error message to set</param>
internal void SetPropertyError(string propertyName, string error)
{
if (propertyErrors.ContainsKey(propertyName))
{
propertyErrors[propertyName] = error;
}
else
{
propertyErrors.Add(propertyName, error);
}
}
#endregion
This works fine when editing existing (i.e. required Properties are valid)
business objects - i.e. if I data bind an ErrorProvider it will show up next
to the respective control and display the appropriate error message in a
tooltip.
The problems I have with this implementation are:
1. If a required property (i.e. EmailAddress, Name etc) starts off with a
null value and the user does not in fact change the value in the data-bound
TextBox, the ErrorProvider will not fire. I know why this is - because I'm
performing my validation in the Set method for the property, but obviously
there has to be a better way to do this.
2. When the user clicks an "OK" button on a data entry form, I can't figure
out how to check whether a validation error has occurred before calling
EndEdit on my binding source.
Is there some validation related interface I'm missing?
Any other ideas/suggestions?