As I am currently developing a Silverlight Application using RIA Services (and Prism), I ran into some little tricks that can really help the developer’s life.

One of the common needs is to force the validation of all fields of an exposed entity in one time, and not just one field just after it has been updated.
This is very important especially when you want to insure our object is strictly validated before submitting changes.

The trick is to create a ValidationContext and manually validate the whole object. The thing to be careful of is not to forget to update the ValidationErrors list of the entity.

[csharp]
public static void Validate(this Entity entity)
{
// prepare the result
var validationResults = new List<ValidationResult>();
// create a validation context
var validationContext = new ValidationContext(entity, null, null);
// validate
Validator.TryValidateObject(entity, validationContext, validationResults);
// reset the validation errors of the entity
entity.ValidationErrors.Clear();
foreach (var error in validationResults)
entity.ValidationErrors.Add(error);
}
[/csharp]

As you can see, I made this method as an extension to the Entity type. So that you can easily use it on every entity you have.

4 thoughts on “Force validation of RIA entities

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s