Data Validation in silverlight

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This

In this article we are going to look at how we can handle errors in silverlight.
This article demonstrates how we can display the custom error message to the user when the validation fails.

In order to receive notification about a validation error that has occurred or has been resolved, we must set the NotifyOnValidationError property to true on the binding object. Setting the NotifyOnValidationError property to true, tells the binding engine to raise the BindingValidationError event when a validation error is added to or removed from the Validation.Errors collection. For example, we can handle the error event to log the error or provide additional visual feedback.

To handle the BindingValidationError event, create an event handler on the target object or any of its parent objects. The BindingValidationError event is a routed event, so if it is not handled on the element that raised the event, it will continue to bubble up to the parent until it is handled.

The following code snippet shows how to provide custom binding validation.

The binding is created in XAML.

1. Add the following namespace and assembly reference to your xaml file where “FirstSilverlightApplication” is your silverlight application name. “my” is the prefix used in our code:


2. Add the following XAML code:

<Grid x:Name="LayoutRoot">

        <StackPanel Orientation="Vertical" >
                <my:Contact x:Name="MyContact"/>
            <TextBox x:Name="txtPhoneNumber" BindingValidationError="txtPhoneNumber_BindingValidationError" Width="200" Margin="10" Height="20">
                    <Binding Mode="TwoWay" Source="{StaticResource MyContact}" 
                     Path="PhoneNumber" NotifyOnValidationError="true"  
            <TextBox Width="200" Height="20" ></TextBox>
                <Button Height="30" Margin="10" Width="150" Content="Click To Update Source"/>

In the above XAML code, we have a “txtPhoneNumber” textbox which has its NotifyOnValidationError=”true” and ValidatesOnExceptions=”true” properties set to true. The textbox is binded to the PhoneNumber property of the Contact class. Contact is embedded as static resource in the stackpanel.
3. Below we have the Contact class definition(Source Object) which throws an exception in the set accessor if the PhoneNumber length is greater than 10.

public class Contact
        private string _PhoneNumber;
        public string PhoneNumber
            get { return _PhoneNumber; }
                if (value.Length > 10)
                    throw new Exception("Phone Number must be 10 digits long.");
                _PhoneNumber = value;

4. Handle the txtPhoneNumber_BindingValidationError event in the Code file as below. Here if there is a validation error, txtPhoneNumber textbox background is set to Red Color indicating an error has occurred.

 private void txtPhoneNumber_BindingValidationError(object sender, ValidationErrorEventArgs e)
            if (e.Action == ValidationErrorEventAction.Added)
                txtPhoneNumber.Background = new SolidColorBrush(Colors.Red);
            else if (e.Action == ValidationErrorEventAction.Removed)
                txtPhoneNumber.Background = new SolidColorBrush(Colors.White);


Run the Application, type in more than 10 digits, to get an error from the source object’s set accessor. Type in less than 10 digits to resolve the validation error. TextBox target-to-source updates occur only when the TextBox loses focus. Another TextBox is provided to change the focus