Menu

CONTROL VALIDATION IN SILVERLIGHT

Data validation is very important for all sort of data driven applications and websites. It is a purifying process where it ensures only valid data is being saved into the database.

By default Silverlight doesn’t give any visual feedback when the data binding system encounters error relating to incorrect input. But what it does is, it rejects data internally.  At this point the user is under the impression that data has been saved.

Yes, it would be nice if the Silverlight data binding engine notify or alert us through visual feedback when there is a violation of rules. Let’s start with simple application which will give us a simple basic ground for future advanced investigation on data validation

Getting Started

Download Source Code => ControlValidationManagement.rar

You need to have Silverlight 3.0 or 4.0 framework installed on your PC for implementation of control validation.
We can create Sliverlight application for control validation.

1.    Create a new Silverlight application.  Open Visual Studio 2010 > File > New Project > Select the language (C# or VB.NET) > Select ‘Silverlight’ in the Project Types > from the templates, select Silverlight Application from the installed templates and enter a name for the application

2.    On clicking OK, To work with the navigation framework, you need to include the “System.Windows.Controls”  and  “System.Windows.Controls.Data.Input” and ” System.ComponetModel.DataAnnotation” assembly reference in your project.

3.     Add the following User class to your project.


using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.ComponentModel.DataAnnotations;

namespace ControlValidationManagement

{

public class User

{

private string _UserName;

private int _Age;

private string _FirstName;

[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;

}

}

 

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

public int Age

{

get

{

return _Age;

}

set

{

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

_Age = value;
}
}
[Required(ErrorMessage = "First Name is required.")]

[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage =

"Numbers and special characters are not allowed in the name.")]

public string FirstName

{
get{
return _FirstName;
}

set

{

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

}

}

}

}

ValidationContext : Initializes a new instance of the ValidationContext class with the specified object to validate.
MemberName : Gets or sets the programmatic name of the member to validate.

4. There you go, XAML. The following section goes between UserControl tags.

<Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>

        <TextBlock Text="User Name" TextWrapping="Wrap" Margin="0" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center"/>
        <TextBox x:Name="txtUserName" Width="100" Margin="0" Grid.Column="1" Grid.Row="0" d:LayoutOverrides="Height" VerticalAlignment="Center" Text="{Binding Path=UserName,Mode=TwoWay,  ValidatesOnExceptions=true, NotifyOnValidationError=true,UpdateSourceTrigger=Explicit}"/>
        <TextBlock Text="First Name" TextWrapping="Wrap" Margin="0" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center"/>
        <TextBox x:Name="FirstName" Width="100" Margin="0" Grid.Column="1" Grid.Row="1" d:LayoutOverrides="Height" VerticalAlignment="Center" Text="{Binding Path=FirstName,Mode=TwoWay,  ValidatesOnExceptions=true, NotifyOnValidationError=true,UpdateSourceTrigger=Explicit}"/>
        <TextBlock HorizontalAlignment="Right" Margin="0" VerticalAlignment="Center" Grid.Row="2" Text="Age" TextWrapping="Wrap" Grid.Column="0"/>
        <TextBox x:Name="txtAge" Margin="0" VerticalAlignment="Center" Grid.Column="1" Grid.Row="2"  Text="{Binding Path=Age,Mode=TwoWay,  ValidatesOnExceptions=true, NotifyOnValidationError=true,UpdateSourceTrigger=Explicit}" Width="100"/>
        <Button x:Name="btnSubmit" Grid.Row="3" Grid.Column="1" Content="Submit" Click="btnSubmit_Click" />
    </Grid>

ValidatesOnExceptions

ValidatesOnExceptions = True, by doing that, it will makes sure silverlight will provide visual feedback for the validation error. This property tells the binding engine that if any sort of exception happens during data transfer to the underlying data source, then treat the exception as a validation error.

Silverlight reports a validation error in the following situations

  1.   Type conversions failure.
  2.   When there is a error in binding object’s set accessor.
  3.   When there is an exception from validation attribute

Key points to remember:

  1. Data binding must be TwoWay
  2. ValidatesOnExceptions = True
  3.  When a TwoWay bound control (in our example, textbox) looses focus, the value gets updated to the source.

UpdateSourceTrigger
UpdateSourceTrigger accepts two values:

  1.   Default
  2.   Explicit

UpdateSourceTrigger = Default indicates automatic update what it was doing until now. UpdateSourceTrigger = Explicit, to disable automatic updates to the binding source. That means, from now on you have to manually update the source. This is useful when user want to perform some sort of activities before the data propagation to source and on demand validation (i.e. in our case Button click event), not when textbox looses focus.

5 .  Now we will see how we could manually update the source which in turns fires the validation process. When user types invalid data and moves to other control, there should be no validation. Now validation only happens in button click.


private void btnSubmit_Click(object sender, RoutedEventArgs e)

{

foreach (var ele in LayoutRoot.Children)

{

if (ele is TextBox)

{

(ele as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource();

}

}

}

Referrals links :=>

http://msdn.microsoft.com/en-us/library/dd901590%28v=vs.95%29.aspx

http://www.codeproject.com/KB/silverlight/SilverlightBindings.aspx

http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesonexceptions%28v=vs.95%29.aspx

http://msdn.microsoft.com/en-us/library/system.windows.data.binding.notifyonvalidationerror%28v=vs.95%29.aspx

http://www.c-sharpcorner.com/uploadfile/dpatra/data-annotations-in-silverlight-3-application/

http://www.codeproject.com/Articles/86955/Silverlight-4-Data-Validation-Tip-of-the-Day-Part

No comments

Leave a Reply


4 × = 24

Categories