(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Data Validation in Silverlight

(7 votes)
Emil Stoychev
>
Emil Stoychev
Joined Oct 15, 2007
Articles:   23
Comments:   98
More Articles
17 comments   /   posted on Mar 20, 2009

This article is compatible with the latest version of Silverlight.

One major point in building line-of-business applications is the data validation. You can’t go without it and that’s where Sillverlight comes in handy. In that release Microsoft added advanced facilities for validating data via two-way databinding.

Following best practices and patterns you may have heard that it is good to separate your validation logic from the UI. That’s exactly the case with the built-in validation in Silverlight.

Let’s start with an example of a data form containing validation logic.

Download source code

OK, looks nice. But how we do that?

The first thing to take care of is the validation rules. To layout our form we use a StackPanel with several other child controls. This StackPanel has a custom class named User set as a DataContext.

 public class User
 {
     public string Name
     {
         get { return name; }
         set
         {
             if ( string.IsNullOrEmpty( value ) )
             {
                 throw new Exception( "Please set a value" );
             }
  
             name = value;
         }
     }
  
    public bool Gender { ... }
  
     public string LikesSilverlight { ... }
  
    public string Attended { ... }
  
     public bool AcceptTerms { ... }
  
     private string name;
     private bool gender;
     private string likesSilverlight;
     private string attended;
     private bool acceptTerms;
 }

We require the user to enter some data for the Name field. In the opposite case we throw an Exception.

Similar approach is applied for the other properties.

Let’s see what we have in the XAML.

 <StackPanel>
     <StackPanel.DataContext>
        <local:User />
     </StackPanel.DataContext>
     <TextBlock Text="Registration Form" FontSize="16"/>
     <TextBlock Text="Name" />
     <TextBox Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True}"/>
     <TextBlock Text="Gender" />
     <StackPanel Orientation="Horizontal">
         <RadioButton GroupName="Gender" Content="Male" IsChecked="True" />
         <RadioButton GroupName="Gender" Content="Female" 
             IsChecked="{Binding Gender, Mode=TwoWay, ValidatesOnExceptions=True}" />
     </StackPanel>
     <TextBlock Text="I Like Silverlight" />
     <ComboBox x:Name="LikesSilverlightCombo" 
         SelectedItem="{Binding LikesSilverlight, Mode=TwoWay, 

                        ValidatesOnExceptions=True, UpdateSourceTrigger=Explicit}">
         <sys:String>Yes</sys:String>
         <sys:String>No</sys:String>
     </ComboBox>
     <TextBlock Text="I've attended" />
     <ListBox SelectionMode="Extended"
         SelectedItem="{Binding Attended, Mode=TwoWay, ValidatesOnExceptions=True}">
         <sys:String>None</sys:String>
         <sys:String>MIX 07</sys:String>
         <sys:String>MIX 08</sys:String>
         <sys:String>MIX 09</sys:String>
     </ListBox>
     <CheckBox x:Name="AcceptTermsCheckBox" Content="Accept Terms" 
         IsChecked="{Binding AcceptTerms, Mode=TwoWay, ValidatesOnExceptions=True}" />
     <Button Content="Register" Click="Validate" 
         IsEnabled="{Binding IsChecked, ElementName=AcceptTermsCheckBox}" />
 </StackPanel>

In all binding expressions we set a new property ValidatesOnExceptions. Setting that property to True will check for exceptions that are thrown during the update of the source property. If an exception is thrown, the binding engine creates a ValidationError with the exception and adds it to the Validation.Errors collection of the bound element. You can see in the example above that if you enter an invalid data in the Name field (i.e. no data in this case), a red border appears in the TextBox and the error message is reported.

Another option you can set is the UpdateSourceTrigger property. It controls the timing of binding source updates. Its default value is Default which returns the default UpdateSourceTrigger value of the target dependency property. For most controls this trigger is fired on PropertyChanged event, however for the TextBox control it is fired on LostFocus.

You can also set UpdateSourceTrigger to Explicit as it is done on the example above on line 17. That means you have to control to manually update the source.

BindingExpression be = this.LikesSilverlightCombo.GetBindingExpression( ComboBox.SelectedItemProperty );
be.UpdateSource(); 

This is useful when doing some time consuming data processing on the background.


Subscribe

Comments

  • -_-

    RE: Data Validation in Silverlight 3


    posted by Bill on Mar 21, 2009 16:59
    Thanks for the explanation.  I like the way they have implemented the validation.

    Minor point:  You have a few typos third to last paragraph (...this triggerr is fired on PorpertyChanged event...).
  • -_-

    RE: Data Validation in Silverlight 3


    posted by memo on Mar 23, 2009 16:09
    Visual studio keeps breaking when the exception is thrown.  How do I avoid this behavior, yet have it still break for other exceptions?
  • emil

    RE: Data Validation in Silverlight 3


    posted by emil on Mar 24, 2009 03:50
    @Bill, thanks, I fixed the typos.

    @Memo, you can avoid that by applying [System.Diagnostics.DebuggerHidden()] attribute on the property. Notice that you may still get the VS Just-in-Time Debugger dialog asking you whether you want to debug it.
  • -_-

    RE: Data Validation in Silverlight 3


    posted by Martin Nyborg on Mar 24, 2009 16:19
    I think that throwing exception for business rules is dead wrong.
  • emil

    RE: Data Validation in Silverlight 3


    posted by emil on Mar 25, 2009 10:34
    Martin, you are somewhat right, but that's the only built-in way to do data validation in that version. Throwing exceptions in proprties just to say 'hey that input is invalid' is not the pretties way to validate user input. I wish we have the opportunety to use IDataErrorInfo, but it seems we have to wait a bit longer.
  • -_-

    RE: Data Validation in Silverlight 3


    posted by McpGza on Mar 25, 2009 11:54
    Hi,

    But there is a new assembly and namespace (System.ComponentModel.DataAnnotations), probably desinged to validation. Do you know about it somtehing? How can it be used?
  • emil

    RE: Data Validation in Silverlight 3


    posted by emil on Mar 26, 2009 05:13
    @McpGza, yes this is used when validating data inside a DataForm. We are preparing an article on this topic. Expect it tomorrow or in the beginning of the next week.
  • -_-

    RE: Data Validation in Silverlight 3


    posted by McpGza on Mar 26, 2009 07:29
    So do you say that these kind of validations (with Custom validation) will be alvailabe only for DataForm?
  • emil

    RE: Data Validation in Silverlight 3


    posted by emil on Mar 27, 2009 02:35
    You can attribute your class' properties, but if there is no one to process them (as with the case of the DataForm) they are just useless. The attributes are processed (read validated) out-of-the box by the DataForm. There is no built-in mechanism that will validate your data by the rules set in the attributes if you don't put your controls inside a DataForm. Of course, you can do that by yourself - write a control that takes those attributes in mind.
  • -_-

    RE: Data Validation in Silverlight 3


    posted by Jon on Apr 02, 2009 19:11
    I agree with the person that said that doing it this way is "dead wrong." I don't think the validation rules should be in the setters of the data model. One place where this becomes problematic is if you are using WCF proxy generated classes where the setters are generated for you. What about ValidationRule like in WPF? I hope Microsoft gets this right because I agree that a "major point in building line-of-business applications is the data validation." I don't think they have it totally right even in WPF, but, not having ValidationRule in Silverlight is worse.
  • -_-

    RE: Data Validation in Silverlight 3


    posted by eye on Apr 23, 2009 10:23
    Nice...and it works!
  • -_-

    RE: Data Validation in Silverlight 3


    posted by Tanmoy on May 27, 2009 00:28
    Right Jon I agree with you. Its a bit problem to have it in auto generated classes.
  • -_-

    RE: Data Validation in Silverlight 3


    posted by jt on Jul 14, 2009 13:38
    what would you suggest for auto generated classes?
  • -_-

    RE: Data Validation in Silverlight 3


    posted by hack2root on Dec 15, 2009 14:00
    Try my demo at

    http://silverlightentityfw.codeplex.com

    I've done validation support also

  • -_-

    RE: Data Validation in Silverlight 3


    posted by panda on Jan 30, 2010 06:00
    hello i am very new to silverlight and i have downloaded the source code and run with visual studio. it throws exceptions...."Unhandled by user code " .......thus i tried adding BindingValidationErrors. But it is not working does anyone knows of other ways to do validations ?  it shouldn't be the way to throw exceptions in setter methods right ? if it is the way ... how do i actually handle the exception
  • -_-

    RE: Data Validation in Silverlight 3


    posted by kiran dada on Feb 12, 2010 13:56

    good

     

  • -_-

    RE: Data Validation in Silverlight 3


    posted by Hardik gheewala on Aug 12, 2010 16:13

    Good solution.

    This really helps me. Happy Codding!!!

Add Comment

Login to comment:
  *      *