SIGN UP MEMBER LOGIN:    
ARTICLE

Data Annotations in Silverlight 3 Application

Posted by Diptimaya Patra Articles | XAML with C# July 27, 2009
Validating user input using Data Annotations in Silverlight 3 Application.
Reader Level:
Download Files:
 

Introduction

In my last article titled "Data Validation In Silverlight 3 Application", we discussed about how we can validate the user input. In this article we will see how Data Annotations help us in validating the data in Silverlight 3 Application.

Crating Silverlight Project

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

image1.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:

    image2.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="#FFE19A76" 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="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"/>
                  <TextBlock HorizontalAlignment="Center" HorizontalAlignment="Left" Width="30" 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

    image3.gif
    In my previous article on Data Validation, I had implemented INotifyPropertyChanged interface. Here we don't need that. We will see how it is not required.
     
  4. Add a Reference to System.ComponentModel.DataAnnotations

    image4.gif
     
  5. Now we will add properties to our UserInfo.cs class.
    As we are following the same user inputs, I am adding the same properites. Follow the code below:

    public
    class UserInfo
        {
            #region UserName
            private string _UserName;
            public string UserName
            {
                get { return _UserName; }
                set { _UserName = value; }
            }
            #endregion

            #region EmailID
            private string _EmailID;
            public string EmailID
            {
                get { return _EmailID; }
                set { _EmailID = value; }
            }
            #endregion

            #region Age
            private string _Age;
            public string Age
            {
                get { return _Age; }
                set { _Age = value; }
            }
            #endregion
        }
     

  6. Now Add required attributes to the properties, for example Required, Range, and RegularExpression etc..

    See the code below how User Name property is being validated. Add the code before the property.

    [Required(ErrorMessage="User Name is Required")]
    [StringLength(12,MinimumLength=6,ErrorMessage="User Name must be in between 6 to 12 Characters")]

     
  7. Add ValidatorProperty method with required parameters.

    [Required(ErrorMessage="User Name is Required")]
            [StringLength(12,MinimumLength=6,ErrorMessage="User Name must be in between 6 to 12 Characters")]
            public string UserName
            {
                get { return _UserName; }
                set
                {
                    Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName="UserName"});
                    _UserName = value;
                }
            }

     
  8. For Email ID validation we need Regular Expression, go ahead write the following code.
     
  9. For Age validation we need Range, add minimum and maximum values.
     

    [Range(18,40,ErrorMessage="Age must be 18 ~ 40")]

            public string Age

            {

                get { return _Age; }

                set

                {
                    Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Age" });
                    _Age = value;
                }
            }
     

  10. Last but not the least add the UserInfo instance to the LayoutRoot's DataContext.

    Remebmer you can add it in two ways, in C# code behind as well as in Xaml. In my last article I added like the following:

    serInfo user = new UserInfo();
    this.LayoutRoot.DataContext = user;

    Now you can do the same thing in XAML too, add the namespace referrence and then do as follows:

    xmlns:myData="clr-namespace:DataAnnotationsInSL3"
    <
    Grid.DataContext>
         <myData:UserInfo />
    </
    Grid.DataContext>

    Now Run your application. Enter wrong input and you will get the error messages.

    image5.gif

That's it we have successfully used Data Annotations to validate user input, and without using INotifyPropertyChanged interface.

Enjoy Coding.


Login to add your contents and source code to this article
share this article :
post comment
 

Hello Diptimaya, Good article. In addition I have a query for you.....how to display same data validation messages for a multilingual application. Please provide me either sample or any article. My email id is nksinghmca@gmail.com

Posted by Neeraj Singh Aug 31, 2011

Diptimaya - Please help. I am now facing a problem because the data-annotations are not being used by the DataForm in my project. I am using Silverlight 4, .NET Framework 4, Visual Web Developer 2010 Express. I have 1 WebApp project, which contains my DataService.svc and Model.edmx and my Self-Tracking-Entities generator Model.TT file, and the Default.aspx that hosts the Silverlight front-end. I have a custom Silverlight Class Library project that has a linked-file pointing to the Model.TT file to expose the classes in a Silverlight-consumable way. I have 1 Silverlight project that has a reference to my custom Silverlight Class Libary project (to be able to reference the entity types) and it has a reference to the DataService.svc and so on. The problem is, I think, is that the data-annotations are not being "carried over" to the Silverlight side-- but, I am not sure why. Must one tell the DataForm to use them in some way? What could be missing? Any help that you can provide is appreciated. Thank you. - Mark Kamoski

Posted by Mark Kamoski Feb 11, 2011

Hello,
is it somehow possible to use localized error message from a resource file or from the db? Setting error messages like "ErrorMessage="Age must be 18 ~ 40"" doesn't help for an international app.

Thanks for your support
Uwe

Posted by Uwe Aug 06, 2009
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Team Foundation Server Hosting
Become a Sponsor