📒
OpenRiaServices
  • Start
  • Prerequisites for Open Ria Services
    • Walkthrough: Installing and Configuring SQL Server 2008 R2 Express with Advanced Services
    • Walkthrough: Installing the AdventureWorks OLTP and LT sample databases
  • Creating Open Ria Services Solutions
    • Walkthrough: Taking a Tour of Open Ria Services
    • Walkthrough: Creating a Open Ria Services Solution
    • Walkthrough: Creating a Open Ria Service with the Code First Approach
    • Walkthrough: Using the Silverlight Business Application Template
    • Walkthrough: Creating a Open Ria Services Class Library
    • Walkthrough: Localizing a Business Application
    • How to: Create a Domain Service that uses POCO-defined Entities
    • How to: Add or Remove a Open Ria Services Link
    • Using the Domain Service Wizard
  • Building Secure Applications with Open Ria Services
  • Deploying and Localizing a Open Ria Services Solutions
    • Troubleshooting the Deployment of a Open Ria Services Solution
    • Troubleshooting the Deployment of a Open Ria Services Solution
    • Walkthrough: Localizing a Business Application
  • Middle Tier
    • Domain Services
      • Walkthrough: Adding Query Methods
      • How to: Add Business Logic to the Domain Service
      • How to: Create a Domain Service that uses POCO-defined Entities
      • How to: Use HTTPS with a Domain Service
    • Data
      • Compositional Hierarchies
      • Presentation Models
      • Inheritance in Data Models
      • Complex Types
      • Shared Entities
      • Walkthrough: Sharing Entities between Multiple Domain Services
      • How to: Add Metadata Classes
      • How to: Validate Data
      • Managing Data Concurrency
    • Shared Code
      • How to: Share Code through Source Files
      • Walkthrough: Creating a Open Ria Services Class Library
  • Silverlight Clients
    • Client Code Generation
    • DomainContext and Operations
    • DomainDataSource
    • Error Handling on the Client
    • Customizing Generated Code
      • How to: Add Computed Properties on the Client
  • Accessing non-Silverlight Clients
    • ASP.NET Clients
    • Walkthrough: Using the Domain Service in ASP.NET Applications
  • Authentication, Roles, and Profiles
    • How to: Enable Authentication in Open Ria Services
    • How to: Enable Roles in Open Ria Services
    • How to: Enable Profiles in Open Ria Services
    • How to: Create a Custom Authorization Attribute
    • Walkthrough: Using Authentication Service with Silverlight Business Application
    • Walkthrough: Using Authentication Service with Silverlight Navigation Application
  • End-to-EndScenarios
    • Walkthrough: Retrieving and Displaying Data From a Domain Service
    • Walkthrough: Editing Data From a Domain Service
    • Walkthrough: Displaying Data in a Silverlight Business Application
    • Walkthrough: Displaying Related Data in a Silverlight Business Application
Powered by GitBook
On this page
  • To add validation attributes provided by Open Ria Services
  • To add a Custom Validation attribute

Was this helpful?

  1. Middle Tier
  2. Data

How to: Validate Data

PreviousHow to: Add Metadata ClassesNextManaging Data Concurrency

Last updated 4 years ago

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.

To add validation attributes provided by Open Ria Services

  1. Add a metadata class for the entity class, as described in .

  2. 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.

    <Required()> _
    <StringLength(60)> _
    Public AddressLine1 As String
    [Required]
    [StringLength(60)]
    public string AddressLine1;
  3. Build (Ctrl+Shift+B) the solution.

  4. 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.

To add a Custom Validation attribute

  1. Add a shared code file by using the *.shared.cs or *.shared.vb naming pattern.

    The code file will contain the custom validation object.

  2. 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.

    Public Class ProductValidator
        Public Shared Function IsProductValid(ByVal productToValidate As Product, ByVal context As ValidationContext)
            If (productToValidate.ListPrice < (CDec(0.8) * productToValidate.StandardCost)) Then
                Return New ValidationResult("ListPrice is below 80 percent of StandardCost.")
            Else
                Return ValidationResult.Success
            End If
        End Function
    End Class
    public class ProductValidator
    {
        public static ValidationResult IsProductValid(Product productToValidate, ValidationContext context)
        {
            if (productToValidate.ListPrice < ((decimal).8 * productToValidate.StandardCost))
            {
                return new ValidationResult("ListPrice is below 80 percent of StandardCost.");
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }
  3. <CustomValidation(GetType(ProductValidator), "IsProductValid")> _
    <MetadataTypeAttribute(GetType(Product.ProductMetadata))> _
    Partial Public Class Product
        Friend NotInheritable Class ProductMetadata
    
            'Metadata classes are not meant to be instantiated.
            Private Sub New()
                MyBase.New()
            End Sub
    
            Public Color As String
    
            Public DiscontinuedDate As Nullable(Of DateTime)
    
            Public ListPrice As Decimal
    
            Public ModifiedDate As DateTime
    
            Public Name As String
    
            Public ProductCategoryID As Nullable(Of Integer)
    
            Public ProductID As Integer
    
            Public ProductModelID As Nullable(Of Integer)
    
            Public ProductNumber As String
    
            Public rowguid As Guid
    
            Public SellEndDate As Nullable(Of DateTime)
    
            Public SellStartDate As DateTime
    
            <Required()> _
            <StringLength(20)> _
            Public Size As String
    
            Public StandardCost As Decimal
    
            Public ThumbNailPhoto() As Byte
    
            Public ThumbnailPhotoFileName As String
    
            Public Weight As Nullable(Of Decimal)
        End Class
    End Class
    [CustomValidation(typeof(RIAServicesExample.Web.SharedCode.ProductValidator), "IsProductValid")]
    [MetadataTypeAttribute(typeof(Product.ProductMetadata))]
    public partial class Product
    {
    
        internal sealed class ProductMetadata
        {
    
            // Metadata classes are not meant to be instantiated.
            private ProductMetadata()
            {
            }
    
            public string Color;
    
            public Nullable<DateTime> DiscontinuedDate;
    
            public decimal ListPrice;
    
            public DateTime ModifiedDate;
    
            public string Name;
    
            public Nullable<int> ProductCategoryID;
    
            public int ProductID;
    
            public Nullable<int> ProductModelID;
    
            public string ProductNumber;
    
            public Guid rowguid;
    
            public Nullable<DateTime> SellEndDate;
    
            public DateTime SellStartDate;
    
            [Required()]
            [StringLength(20)]
            public string Size;
    
            public decimal StandardCost;
    
            public byte[] ThumbNailPhoto;
    
            public string ThumbnailPhotoFileName;
    
            public Nullable<decimal> Weight;
        }
    }
  4. 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.

Release Notes
Changelog
CustomValidationAttribute
DataTypeAttribute
RangeAttribute
RegularExpressionAttribute
RequiredAttribute
StringLengthAttribute
How to: Add Metadata Classes
How to: Add Metadata Classes
RequiredAttribute
StringLengthAttribute
How to: Add Metadata Classes
ValidationResult
CustomValidationAttribute
CustomValidationAttribute
CustomValidationAttribute