How to: Validate Data
Last updated
Was this helpful?
Last updated
Was this helpful?
[ This document was written for WCF Services Version 1 Service Pack 2 and might not be up to date Please see or for a list of changes since WCF RIA Services ]
This topic describes how you add validation attributes to properties and entities to enforce validation rules. Open Ria Services provides several validation attributes that perform common validation checks, and also provides the attribute to enable you to specify customized validation checks.
The following default validation attributes are provided by Open Ria Services:
You add the validation attributes to entities in the server project and those validation attribute are propagated to their generated client entity representations. At runtime, the validation rules are applied to data from the user. You must add metadata classes to add validation attributes. For more information on how to do this, see .
This topic describes how to add default and custom validation attributes.
Add a metadata class for the entity class, as described in .
On the properties or entity that you want to validate, add the validation attributes that perform the validation.
The following example shows the and attributes applied to a property named AddressLine1.
Build (Ctrl+Shift+B) the solution.
In the Silverlight application, open the generated code file in the Generated_Code folder, and notice how the validation attributes have been applied in the client code.
Add a shared code file by using the *.shared.cs or *.shared.vb naming pattern.
The code file will contain the custom validation object.
Add a method that determines whether the data is valid.
The following example shows a class named ProductValidator with a method named IsProductValid that validates a Product entity. When the data is not valid, you return the error message and the name of the property that failed validation.
Build (Ctrl+Shift+B) the solution.
Add a metadata class for the entity class, as described in .
The method must be public and static (or Public and Shared in Visual Basic). It must return a to indicate the result of the validation check. When you define the customized validation class, you must provide at least some code other than auto-implemented properties for the class to be correctly generated in the client project.
On the entity or property that you want to validate, add the attribute and pass the type of the validation object and the name of the method that performs the validation.
The following example shows the attribute applied to an entity. The validation object type is ProductValidator and the method is IsProductValid.
In the Silverlight application, open the Generated_Code folder. Notice the shared code file exists in the folder and how the is applied to the entity.