It used to be simple. We'd write a desktop application and write code in the UI that ensured a user didn't give us bad data. In those days a one-tier or two-tier application was common, and doing the validation directly in the UI was adequate. But much has changed. For more information on Silverlight, see "Sizing Up Client Development Choices: XAML-Silverlight or JavaScript-HTML5" and "The Case for Silverlight in a HTML5 World."

Now that we're separating our UI from our data, it's becoming increasingly important to have a simple system for gathering validation errors and displaying them to users. This is especially interesting because we need to validate our data on the client and on the server. Since Silverlight 3, Microsoft has invested in making this easier.  Let's look at how data validation works now in Silverlight.

How Silverlight Validation Works

In Silverlight 4 (and 3) most edit controls include implicit support for exposing validation errors directly to a user via the user interface.  In Figures 1 and 2, you can see how the default TextBox shows validation errors.

Figure 1: Valid Data

The look of the validation is exposed directly in the ControlTemplate of most controls, so that you can style the validation look just like any other part of a control.  Typically, this is implemented as a VisualStateManager group. Because the controls can now support showing validation errors, you'll need a systematic way of exposing validation errors to the user interface.

Figure 2: Invalid Data

Validation in Silverlight 3

Silverlight 3 is the first release that included these validation-friendly controls. To take advantage of the controls' validation features, data binding included two important properties of the markup extension: NotifyOnValidationError and ValidatesOnExceptions. The following code shows a simple set of controls using these binding properties to enable showing validation errors:

  1. <TextBox Text="{Binding Name, Mode=TwoWay,
  2.                         ValidatesOnExceptions=True,
  3.                         NotifyOnValidationError=True}" />

The NotifyOnValidationError property allows the BindingValidationError event to be called when a validation error happens. The BindingValidationError event could be caught directly by you but more commonly it's caught by the validation infrastructure so that you can show the validation error. But when does a validation error actually happen? That's where the ValidatesOnExceptions property comes in. This property tells the control that if an exception happens during transfer of the property back to the underlying data source, then treat the exception as a validation error. For example, if we have a simple class with a Name property, we could throw an exception in the setter of the Name property if it was blank (since it's required).  You can see this code in Figure 3.

  1. public class Game
  2. {
  3.   string _name;
  4.   public string Name
  5.   {
  6.     get
  7.     {
  8.       return _name;
  9.     }
  10.     set
  11.     {
  12.       if (string.IsNullOrEmpty(value))
  13.       {
  14.         throw new ValidationException("Name is required");
  15.       }
  16.       _name = value;
  17.     }
  18.   }
  19. ...
  20. }

Figure 3 shows validation of the new Name value and throwing an exception if it is invalid. While this example shows a ValidationException being thrown, any exception will be treated as a validation error. To make this simpler, a number of attributes exist in the System.ComponentModel.DataAnnotations namespace. For example, you can use the Required attribute to get the same behavior we had before, as shown in Figure 4.

  1. public class Game
  2. {
  3.   string _name;
  5.   [Required]
  6.   public string Name
  7.   {
  8.     get
  9.     {
  10.       return _name;
  11.     }
  12.     set
  13.     {
  14.       _name = value;
  15.     }
  16.   }
  17. ...
  18. }

These validation attributes let you specify the error message or, alternatively, an error message resource name and type (to make localizing the error messages easy). These validation attributes are shown in Figure 5.

Attribute Description
Figure 5: Validation Attributes
Required Specifies that a property is required (e.g. not empty or not null).
StringLength Specifies that a string has a limitation on the size of a string, including both a minimum and a maximum size.
Range Specifies that a property has a range of valid values. Typically used with numeric or date data types.
RegularExpression Specifies that the property can be validated by comparing it against a supplied regular expression.
CustomValidation Specifies that a supplied method should be consulted to perform validation.

These attributes are really helpful in performing property validation.  But simply placing them on the properties does not do the trick. You'll need to fire off the validation inside each of your property setters. You can do this with the ValidationContext and Validator classes, as shown in Figure 6.

  1. [Required]
  2. public string Name
  3. {
  4.   get
  5.   {
  6.     return _name;
  7.   }
  8.   set
  9.   {
  10.     // Use the Validation classes to
  11.     // validate against attribute
  12.     var ctx = new ValidationContext(this, null, null);
  13.     ctx.MemberName = "Name";
  14.     Validator.ValidateProperty(value, ctx);
  16.     _name = value;
  17.   }
  18. }

The ValidationContext needs to contain a reference to the object to be validated and the member name to be validated.  Calling the Validator.ValidateProperty static method checks the proposed value against any and all validation attributes. If it fails, it throws a ValidationException so that it is propagated to the control(s).

This validation strategy seems simple if you're building your own client-side classes but, in practice, it's not a viable strategy. The problem is that most of our bound data is coming in the form of data from the server. This data is exposed as code-generated classes and these code-generated files make it difficult to add these attributes and the validation code. One solution is to use WCF RIA Services as your data layer.

By using WCF RIA Services to wrap your server-side code, the client-side code that is generated will include both the attributes and generated code in the client to force the validation. For example, in our client-side Game class, our Name property is not only automatically annotated with the attributes, it calls a method inside the setter to perform the data validation (as seen in Figure 7).

  1. [DataMember()]
  2. [Description("The Name of the Game")]
  3. [Required()]
  4. [StringLength(100)]
  5. public string Name
  6. {
  7.     get
  8.     {
  9.         return this._name;
  10.     }
  11.     set
  12.     {
  13.         if ((this._name != value))
  14.         {
  15.             this.ValidateProperty("Name", value);
  16.             this.OnNameChanging(value);
  17.             this.RaiseDataMemberChanging("Name");
  18.             this._name = value;
  19.             this.RaiseDataMemberChanged("Name");
  20.             this.OnNameChanged();
  21.         }
  22.     }
  23. }

Explaining how WCF RIA Services works is outside the scope of this article, but if you want to use these attributes without having to create your own client-side classes, WCF RIA Services is the most straightforward way to accomplish that in Silverlight 3.

The reality is that the Silverlight 3 solution for validation does not go far enough. It assumes that property-level validation is all that is needed. In addition, it forces you to use a specific data layer to get any real functionality. While the appearance of validation in Silverlight 3 was helpful, it was severely handicapped by how it worked. Luckily for us, in Silverlight 4 this has changed.

Changes for Silverlight 4

This problem of surfacing validation errors is not new. In fact, in Windows Forms, this problem was solved with a simple interface called IDataErrorInfo. This interface exposes a way to communicate errors back to a UI container about errors on the object. When Silverlight 3 announced its validation framework, many developers asked why not just support IDataErrorInfo, since it's a well-worn way to communicate validation errors. In Silverlight 4, Microsoft did just that—but also went beyond that simple support.

The IDataErrorInfo interface is simple; it has an interface for retrieving object- and property-level validation errors, as seen in the following code:

  1. public interface IDataErrorInfo
  2. {
  3.   string Error { get; }
  4.   string this[string columnName] { get; }
  5. }

The Error property should have object-level validation information while this property supports retrieving validation errors about specific "columns" of data.  Since it is an interface, it becomes trivial to add to the partial classes that are created by WCF Services, WCF Data Services, or even WCF RIA Services. But because this validation information is not communicated though exceptions, we can implement it by validating the actual data. Figure 8 shows an example implementation.

  1. public partial class Game : IDataErrorInfo
  2. {
  4.   string IDataErrorInfo.Error
  5.   {
  6.     get
  7.     {
  8.       if (Description.CompareTo(Name) == 0)
  9.       {
  10.         return "Description and Name cannot be the same string";
  11.       }
  12.       return "";
  13.     }
  14.   }
  16.   string IDataErrorInfo.this[string columnName]
  17.   {
  18.     get
  19.     {
  20.       switch (columnName)
  21.       {
  22.         case "Name":
  23.           {
  24.             if (string.IsNullOrEmpty(Name))
  25.             {
  26.               return "Name is Required";
  27.             }
  28.             break;
  29.           }
  30.         default:
  31.           break;
  32.       }
  34.       return "";
  35.     }
  36.   }
  37. }

To use this interface, you must tell the data bindings that you expect your object to have an IDataErrorInfo interface implementation. To do this, add the ValidatesOnDataErrors property on the binding as shown in the code below:

  1. <TextBlock>Name</TextBlock>
  2. <TextBox Text="{Binding Name, Mode=TwoWay,
  3.                         ValidatesOnDataErrors=True,
  4.                         NotifyOnValidationError=True}" />

This introduces a troubling problem. Using different binding properties to indicate the different types of validation implies that my UI must know how my underlying objects are going to relate their validation errors. This troubles me but currently this is just the way it is implemented, so we're going to have to live with it.

The indexer for the interface makes it relatively simple to check for valid data and return the appropriate property-level validation. This interface works well for communicating the property- or column-level validation errors, but the object-level validation leaves a bit to be desired. In fact, this interface is included to use existing implementations that already expose this interface. For new development, the Silverlight team has come up with a better solution: the INotifyDataErrorInfo interface.

The INotifyDataErrorInfo interface is a better fit for Silverlight because it allows for asynchronous validation (to support server-side validation). The INotifyDataErrorInfo interface supports the interface shown in the following code:

  1. public interface INotifyDataErrorInfo
  2. {
  3.   bool HasErrors { get; }
  5.   event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
  7.   IEnumerable GetErrors(string propertyName);
  8. }

The big difference in this interface and IDataErrorInfo is the inclusion of an event to let the listener know that the errors have changed. In addition, instead of an indexer for retrieving the errors, it changes this to a method because the results may be different based on when you call it.  Note that the GetErrors method returns a list of errors instead of a simple string, because a property may have more than one error to address. Currently, passing in an empty string or a null for the propertyName should return object-level validation errors. So this method is there to handle property- and object-level validation.

Note that the example shows a Dictionary that contains a list of errors for each property name. That way when we implement HasErrors and GetErrors, we can simply refer to this list of errors. While it might seem simpler to check during GetErrors or HasErrors, this pattern is especially crucial for asynchronous support for validation (e.g., going to a server to retrieve the status of a property or the object). Figure 9 shows a web service being called to validity of the ReleaseDate as it changes.

  1. public partial class Game : INotifyDataErrorInfo
  2. {
  4.   Dictionary<string, ObservableCollection<string>> errors;
  6.   Dictionary<string, ObservableCollection<string>> AsyncErrors
  7.   {
  8.     get
  9.     {
  10.       if (errors == null)
  11.       {
  12.         errors = new Dictionary<string, ObservableCollection<string>>();
  13.       }
  15.       return errors;
  16.     }
  17.   }
  19.   event EventHandler<DataErrorsChangedEventArgs> errorsChanged;
  20.   event EventHandler<DataErrorsChangedEventArgs> INotifyDataErrorInfo.ErrorsChanged
  21.   {
  22.     add
  23.     {
  24.       errorsChanged += value;
  25.     }
  26.     remove
  27.     {
  28.       errorsChanged -= value;
  29.     }
  30.   }
  32.   IEnumerable INotifyDataErrorInfo.GetErrors(string propertyName)
  33.   {
  34.     if (!AsyncErrors.ContainsKey(propertyName))
  35.     {
  36.       AsyncErrors.Add(propertyName, new ObservableCollection<string>());
  37.     }
  38.     return AsyncErrors[propertyName];
  39.   }
  41.   bool INotifyDataErrorInfo.HasErrors
  42.   {
  43.     get
  44.     {
  45.       return AsyncErrors.Where(d => d.Value.Count() > 0).Any();
  46.     }
  47.   }
  48. }

In the callback from the web service, we add the error to the collection of errors and throw the event so that anyone who is listening for the change will be alerted to get a new list. This is shown in Figure 10. By including the new interfaces in Silverlight 4, we can handle validation in many other scenarios that were simply impossible in prior versions.

  1.   partial void OnReleaseDateChanged()
  2.   {
  3.     var client = new GamesServiceClient();
  4.     client.CheckReleaseDateCompleted += OnCheckReleaseDateComplete;
  5.     client.CheckReleaseDateAsync(ReleaseDate);
  6.   }
  8.   void OnCheckReleaseDateComplete(object s, CheckReleaseDateCompletedEventArgs e)
  9.   {
  10.     if (e.Error != null || !e.Result)
  11.     {
  12.       AsyncErrors["ReleaseDate"].Add("Release Date is not valid.");
  14.       if (!AsyncErrors.ContainsKey("ReleaseDate"))
  15.       {
  16.         AsyncErrors["ReleaseDate"] = new ObservableCollection<string>();
  17.       }
  19.       if (errorsChanged != null)
  20.       {
  21.         errorsChanged(this,
  22.           new DataErrorsChangedEventArgs("ReleaseDate"));
  23.       }
  24.     }
  25.     else
  26.     {
  27.       if (AsyncErrors["ReleaseDate"].Count > 0)
  28.       {
  29.         AsyncErrors["ReleaseDate"].Clear();
  31.         if (errorsChanged != null)
  32.         {
  33.           errorsChanged(this,
  34.             new DataErrorsChangedEventArgs("ReleaseDate"));
  35.         }
  36.       }
  37.     }
  38.   }

Where We Are

Because Silverlight is touted as a solution for building line-of-business applications, data validation is crucial to streamlining development. Starting in Silverlight 3, we can see the beginnings of a real validation framework. Now that we are approaching Silverlight 4, the validation framework is maturing so that it can be used by more than simple applications.

The new interfaces introduced in Silverlight 4 allow us to use existing code (that may use the IDataErrorInfo interface) and to start exposing validation from our new objects (via INotifyDataError). Because the controls now support this validation, we can expose validation errors directly to our users.

Shawn Wildermuth ( is president of COM Guru, a Boston area consulting company that develops large-scale websites and Windows 2000 implementations.