Custom validation with WCF RIA

Just a small post about custom validation attribute for WCF RIA.

Sometimes the standard validation rules are not enough. I’ll explain how easily create custom rules.

First step is very easy : just add a class on the server side.

IMPORTANT : the class file must end with “.shared.cs” otherwise the code will not be copied to the client.

Alternatively, you can use a normal name and make a link from the client project to that new class. The advantage is that it is more clear (you see the file on the client project, where, with the “*.shared.cs” you don’t see it, so it can be confusing).

Now, in your class you must add a public static method with two parameters : the first one is the type of the field (or the class) you want to validate, the second is a ValidationContext type.

Example :

using System.ComponentModel.DataAnnotations;

namespace Web
{
    public class CustomValidation
    {
        public static ValidationResult CityCustomValidation(string city, ValidationContext context)
        {
            if (city.ToUpper() == "BRUSSELS")
                return new ValidationResult("City cannot be BRUSSELS");
            return ValidationResult.Success;
        }
    }
}

If validation successful, return a ValidationResult.Success, otherwise return a new ValidationResult with the error message.

Now, to tell WCF RIA we want to use that rule, just add a new CustomAttribute on the field (or class) in the metadata file.

Example :

namespace Web
{
    using System.ComponentModel.DataAnnotations;


    // The MetadataTypeAttribute identifies CustomersMetadata as the class
    // that carries additional metadata for the Customers class.
    [MetadataTypeAttribute(typeof(CustomersMetadata))]
    public partial class Customers
    {

        internal sealed class CustomersMetadata
        {

            // Metadata classes are not meant to be instantiated.
            private CustomersMetadata()
            {
            }

            public string Address { get; set; }
            [CustomValidation(typeof(CustomValidation), "CityCustomValidation")]
            public string City { get; set; }

            ...
        }
    }
}

The first parameter of the CustomValidation is the type of the validation class, and the second one is the method to use.

Now if we try to put Brussels as a city we have :

Very basic example, but it is a good starting point.

The example sources (Client + server) :

Sources

Note : I use the famous Northwind DB, it should be installed beforehand.

The following two tabs change content below.
Olivier

Olivier

Mobile Engineer at Arcana Studio
Freelance developer. Passionate for mobile Development and IoT. Expert in WinRT and Xamarin. MVP Windows Platform Development Nokia Developer Champion