Data Validation in Silverlight 3

  
Introduction

Data Validation, in an ASP.NET site you can easily implement the Data Validation using the Validation options like Required Field Validator, Range Validator so and so forth. So the basic question that comes to our mind is that can we achieve that in Silverlight 3. The answer is yes. In this article you will se how we can validate the user input.

Creating Silverlight Project

Fire up Visual Studio 2008 and create a Silverlight Application. Name it as DataValidationSL3.

1.gif
 
To make the application look good I am going to design it in Blend 3, don't worry this will be a simple design.

  1. Open the Solution in Blend 3.
     
  2. Add few TextBlocks, TextBoxes.

    The MainPage.xaml will look like as follows:

    2.gif

    As you see from the above figure, I have 3 text boxes for User Name, Email ID, and Age. I have 2 Password Boxes for Password and confirm Password. All arefor User Input.

    Now design part is done open the solution in Visual Studio Again. Here is the Xaml Code after designing.


    <
    Grid x:Name="LayoutRoot">

              <Grid.RowDefinitions>

                       <RowDefinition Height="0.112*"/>

                       <RowDefinition Height="0.081*"/>

                       <RowDefinition Height="0.058*"/>

                       <RowDefinition Height="0.054*"/>

                       <RowDefinition Height="0.052*"/>

                       <RowDefinition Height="0.056*"/>

                       <RowDefinition Height="0.056*"/>

                       <RowDefinition Height="0.529*"/>

              </Grid.RowDefinitions>

              <Grid.ColumnDefinitions>

                       <ColumnDefinition Width="0.333*"/>

                       <ColumnDefinition Width="0.022*"/>

                       <ColumnDefinition Width="0.312*"/>

                       <ColumnDefinition Width="0.333*"/>

              </Grid.ColumnDefinitions>

              <Grid.Background>

                       <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                                 <GradientStop Color="#FF67CBA7" Offset="1"/>

                                 <GradientStop Color="White"/>

                       </LinearGradientBrush>

              </Grid.Background>

              <TextBlock Text="User Name" TextWrapping="Wrap" Margin="0" Grid.Row="2" HorizontalAlignment="Right" VerticalAlignment="Center"/>

              <TextBlock HorizontalAlignment="Right" Margin="0" VerticalAlignment="Center" Grid.Row="3" Text="Email ID" TextWrapping="Wrap"/>

              <TextBlock HorizontalAlignment="Right" Margin="0" VerticalAlignment="Center" Grid.Row="4" Text="Password" TextWrapping="Wrap"/>

              <TextBlock HorizontalAlignment="Right" Margin="0" VerticalAlignment="Center" Grid.Row="5" Text="Confirm Password" TextWrapping="Wrap"/>

              <TextBlock HorizontalAlignment="Right" Margin="0" VerticalAlignment="Center" Grid.Row="6" Text="Age" TextWrapping="Wrap"/>

              <TextBox x:Name="txtUserName" TextWrapping="Wrap" Margin="0" Grid.Column="2" Grid.Row="2" d:LayoutOverrides="Height" VerticalAlignment="Center"/>

              <TextBox x:Name="txtEmailID" Margin="0" VerticalAlignment="Center" Grid.Column="2" Grid.Row="3" TextWrapping="Wrap"/>

              <TextBox x:Name="txtAge" Margin="0" VerticalAlignment="Center" Grid.Column="2" Grid.Row="6" TextWrapping="Wrap"/>

              <PasswordBox x:Name="txtPass" Margin="0" Grid.Column="2" Grid.Row="4" d:LayoutOverrides="Height" VerticalAlignment="Center"/>

              <PasswordBox x:Name="txtPassConf" Margin="0" VerticalAlignment="Center" Grid.Column="2" Grid.Row="5"/>

              <TextBlock HorizontalAlignment="Center" VerticalAlignment="Top" Text="Data Validation Sample" TextWrapping="Wrap" Grid.Column="2" FontSize="16"/>

              <TextBlock HorizontalAlignment="Center" VerticalAlignment="Top" Grid.Column="2" FontSize="13.333" Text="User Information" TextWrapping="Wrap" Grid.Row="1"/>
      </Grid>

     

  3. Now we will add a class to the Silverlight Project and Name is UserInfo.cs

    3.gif
     
  4. We will implement INotifyPropertyChanged interface to view the notifications.
     
  5.  Add a method that can notify when there is a property change.

    private
    void RaisePropertyChanged(string propertyName)


            {

                if (this.PropertyChanged != null)

                {

                    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

                }

            }

  6. Add properties and required logic to validate the user input.
    #region UserName

            private string _UserName;

            public string UserName

            {

                get { return _UserName; }

                set

                {

                    if (value.Length < 6)

                    {

                        throw new ArgumentException("User Name should contain atleast 6 chars");

                    }

                    _UserName = value;

                    RaisePropertyChanged("UserName");

                }

            }

            #endregion

     

            #region EmailID

            private string _EmailID;

            public string EmailID

            {

                get { return _EmailID; }

                set

                {

                    string emailId = value.ToString();

     

                    if (!emailId.Contains("@") && !emailId.Contains("."))

                    {

                        throw new ArgumentException("Email ID is Invalid");

                    }

     

                    _EmailID = value;

                    RaisePropertyChanged("EmailID");

                }

            }

            #endregion

     

            #region Password

            private string _Password;

            public string Password

            {

                get { return _Password; }

                set { _Password = value; }

            }

            #endregion

     

            #region PasswordCon

            private string _PasswordCon;

            public string PasswordCon

            {

                get { return _PasswordCon; }

                set

                {

                    if (value!=PasswordCon)

                    {

                        throw new ArgumentException("Type Same Password");

                    }

     

                    _PasswordCon = value;

                    RaisePropertyChanged("PasswordCon");

                }

            }

            #endregion

     

            #region Age

            private string _Age;

            public string Age

            {

                get { return _Age; }

                set

                {

                    if (Convert.ToInt32(value) < 18 || Convert.ToInt32(value)>40)

                    {

                        throw new ArgumentException("Your Age must be in the Range 18 ~ 40");

                    }

                    _Age = value;

                    RaisePropertyChanged("Age");

                }

            }        
    #endregion

     

  7. Now time to bind these properties with the Xaml controls we have. Do as following.
     

    <TextBox x:Name="txtUserName" TextWrapping="Wrap" Margin="0" Grid.Column="2" Grid.Row="2" d:LayoutOverrides="Height" VerticalAlignment="Center">

                <TextBox.Text>

                    <Binding Mode="TwoWay" Path="UserName" NotifyOnValidationError="True" ValidatesOnExceptions="True"/>

                </TextBox.Text>

            </TextBox>

    <TextBox x:Name="txtEmailID" Margin="0" VerticalAlignment="Center" Grid.Column="2" Grid.Row="3" TextWrapping="Wrap">

                <TextBox.Text>

                    <Binding Mode="TwoWay" Path="EmailID" NotifyOnValidationError="True" ValidatesOnExceptions="True"/>

                </TextBox.Text>

    </TextBox>

    <TextBox x:Name="txtAge" Margin="0" VerticalAlignment="Center" Grid.Column="2" Grid.Row="6" TextWrapping="Wrap">

            <TextBox.Text>

                    <Binding Mode="TwoWay" Path="Age" NotifyOnValidationError="True" ValidatesOnExceptions="True"/>

                </TextBox.Text>

    </TextBox>

    <PasswordBox x:Name="txtPassConf" Margin="0" VerticalAlignment="Center" Grid.Column="2" Grid.Row="5">

                <PasswordBox.Password>

                    <Binding Mode="TwoWay" Path="PasswordCon" NotifyOnValidationError="True" ValidatesOnExceptions="True"/>

                </PasswordBox.Password>
    </PasswordBox>
     

  8. Now add the instance of the UserInfo class to the DataContext of the LayoutRoot Grid in MainPage.xaml.cs.

    UserInfo info = new UserInfo();
    LayoutRoot.DataContext = info;
That's it now we are ready with our demo. Press F5 to run in Debug mode or you can try with Start without Debugging (Ctrl + F5).

You will see the error messages that you have provided in the properties in a red box which can be shown when you mouse hover onto it.

The following error messages will be thrown when there is an error with the user input.
 
 4.gif 
 
These are the error messages when you mouse over the red flag on the top right corner of the input.

The following figure displays when nothing is hovered.

5.gif
 
That's it. We have successfully imlemented input validation in Silverlight 3.

Enjoy Coding! 


Recommended Free Ebook
Similar Articles