August 29, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Implementing Data Validation in Silverlight

  • May 30, 2011
  • By Arun Karthick
  • Send Email »
  • More Articles »

In this article I will explain the concept of data validation in Silverlight 4.0 applications. I will also provide sample code to help you understand the functionality. Data validation is always an important task while developing an application of any sort. Below are some major reasons which I think to be the need for proper data validation in an application.

  • To prevent the data store from being corrupted.
  • To maintain the application type safety.
  • To provide some valid constraints for the end user during the process of entering the data and there by receiving the data in a valid format as the application expects.

It is important that the data validation functionality not only validates the input data but also points out the mistakes from the end user in a meaningful way, which in turn helps them fix the issue.

Data validation in Silverlight

Unlike the other .net applications in Silverlight, the data validation can be implemented directly in the business object whose properties are set as binding elements of a Silverlight control. The idea is that the data validation for the property is performed as the user provides the input. Based on the validation result, an appropriate error message is displayed on the respective control.

In Silverlight 4.0 an interface named IDataErrorInfo has been made available under the System.ComponentModel namespace to facilitate the data validation process. The interface declares a property named Error and an indexer. The business object which needs to hold the validation of the data set to its properties should implement the IDataErrorInfo interface.

Sample Data Validation code

In this section we will create a sample application, implement data validation using IDataErrorInfo interface and walk through the code.

Create a Silverlight application using Visual Studio 2010 and add a Business Entity class to it called Employee. Implement the IDataErrorInfo interface in that class like this.

public class Employee : IDataErrorInfo
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    private int _age;
    public string Age { get; set; }
    public string Department { get; set; }

    #region IDataErrorInfo Members

    public string Error
    {
        get
        {
            return null;
        }
    }

    public string this[string property]
    {
        get
        {
            switch (property)
            {
                case "FirstName":
                    if (string.IsNullOrEmpty(FirstName))
                        return "FirstName is required";
                    break;
                case "Age":
                    if (string.IsNullOrEmpty(Age))
                        return "Age is required";
                    else if (!int.TryParse(Age, out _age))
                        return "Age should be numeric";
                    break;
                default:
                    break;
            }

            return null;
        }
    }

    #endregion
}

Notice that in the above class the data validation is implemented in the indexer using a switch case based on the property name for which the data value is being set.

In the MainPage.xaml add few text boxes to accept the data from the end user. Below is the XAML code.

<UserControl x:Class="DataValidationSample.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d"

d:DesignHeight="270" d:DesignWidth="596" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

<Grid x:Name="LayoutRoot" Background="White">

<sdk:Label Height="28" HorizontalAlignment="Left" Margin="188,0,0,0" Name="TitleLabel" Content="New Employee Form" VerticalAlignment="Top" FontSize="16" Width="184" />

<TextBox Height="23" HorizontalAlignment="Left" Margin="252,49,0,0" Text="{Binding FirstName,Mode=TwoWay,ValidatesOnDataErrors=True}" Name="FirstNameTextBox" VerticalAlignment="Top" Width="166" />

<TextBox Height="23" HorizontalAlignment="Left" Margin="252,88,0,0" Text="{Binding LastName,Mode=TwoWay,ValidatesOnDataErrors=True}" Name="LastNameTextBox" VerticalAlignment="Top" Width="166" />

<TextBox Height="23" HorizontalAlignment="Left" Margin="252,128,0,0" Text="{Binding Age,Mode=TwoWay,ValidatesOnDataErrors=True}" Name="AgeTextBox" VerticalAlignment="Top" Width="69" />

<TextBox Height="23" HorizontalAlignment="Left" Margin="252,167,0,0" Text="{Binding Department,Mode=TwoWay,ValidatesOnDataErrors=True}" Name="DepartmentTextBox" VerticalAlignment="Top" Width="166" />

<Button Content="Submit" Height="23" HorizontalAlignment="Left" Margin="252,211,0,0" Name="SubmitButton" VerticalAlignment="Top" Width="75" />

<sdk:Label Height="28" HorizontalAlignment="Left" Margin="91,49,0,0" Name="FirstNameLabel" Content="First Name:" VerticalAlignment="Top" Width="120" />

<sdk:Label Height="28" HorizontalAlignment="Left" Margin="91,88,0,0" Name="LastNameLabel" Content="Last Name:" VerticalAlignment="Top" Width="120" />

<sdk:Label Height="28" HorizontalAlignment="Left" Margin="91,128,0,0" Name="AgeLabel" Content="Age:" VerticalAlignment="Top" Width="120" />

<sdk:Label Height="28" HorizontalAlignment="Left" Margin="91,167,0,0" Name="DepartmentLabel" Content="Department:" VerticalAlignment="Top" Width="120" />

</Grid>

</UserControl>

The above text boxes are bound the specific data fields using the Binding property. It is important to set the attribute ValidatesOnDataErrors to True. The data context has to be set in the MainWindow.xaml.cs file.

public partial class MainPage : UserControl
{
    Employee _employee = new Employee();
    public MainPage()
    {
        InitializeComponent();
        this.DataContext = _employee;
    }
}

Run the application. Fig 1.0 shows the output screen. Notice the require fields are already highlighted and hovering on which the error message is displayed.


Figure 1

Fig 1.0

For the Age property we have two validations: one is the require field validation and the other is the numeric field validation. So when you start entering alpha numeric data in the AgeTextBox the numeric value will be shown as seen in Fig 2.0

Figure 2

Fig 2.0

Conclusion

I hope this article has provided you with the basic info about how to perform basic data validations in a Silverlight 4.0 application. Please make use of the comments sections to provide feedback. In my future articles I will write about data validations such as validating the entered data against the database asynchronously and so on.

Happy reading!

 

 


Tags: Silverlight, tutorial, data validation, concept of data validatio

Originally published on http://www.developer.com.


Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel