[RIA Services] How to force the validation of my entities (and just the validation !)
19 October 2010RIA services solves for you a lot of problems and one of them is to add validations rules on the entities both on the client and on the server side. These differents rules are checked when you submit the changes from the client to the server or when you call “EndEdit” on the entities.
But there is times when you want to leverage the validation without submit the changes or commit your object modification (in a IEditableObject way of talking). In this post we will discover how to do just this.
Why don’t just call EndEdit() by the way ? Because by doing so you may push entities which are in a wrong state into the domain context with no way to revert to a correct state. Indeed, although the EndEdit method of the RIA entities launch the validation process and update the validations errors it does not stop the EndEdit from being performed even if there is errors.
So it may be a better idea to check if the Entity is in a correct state (no validation errors) before to call the EndEdit.
The little snippet to use is very simple and straightforward and it works well with the Silverlight toolkit dataform (if needed). It use the Validator class from the same assembly in which are the differents validations sttributes : System.ComponentModel.DataAnnotations.
/// <summary>
/// Validates the item and add its error in its validationErrors list.
/// </summary>
/// <param name="dataToValidate">The data to validate.</param>
/// <returns><code>True</code> if the object is valid, false otherwise.</returns>
public static bool ValidateItem(Entity dataToValidate,
out ICollection<ValidationResult> validationResults)
{
if (dataToValidate == null)
throw new ArgumentNullException("dataToValidate");
validationResults = new List<ValidationResult>();
ValidationContext context = new ValidationContext(dataToValidate, null, null);
Validator.TryValidateObject(dataToValidate, context, validationResults, true);
dataToValidate.ValidationErrors.Clear();
foreach (var res in validationResults)
{
dataToValidate.ValidationErrors.Add(res);
}
return validationResults.Count == 0;
}
Comments
Great tip!
thanks!
@seba : thank you !
Is there an easy way to get this to traverse all child ComplexObjects? Eg My Top level Entity contains several ComplexObject instances, all of which have their own validation attributes. I want to validate all the way down...
@Paul :You may have to create a special ValidationAttribute just for this of iterate on the complex entities...
Ignorent Question:
I am new to validation & just implemented the client-side validation async.
Where to define that method and where to call it ?
Regards
how easy it can be - thx a lot!
Man : you are the best :D
After 2 days of website research and testing code sample with failed result for my Silverlight app need,
I found your post and the job is done :D
Congratz !
Wlad