Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

(untagged)

Silverlight 4 : Data Validation - Tip of the Day - Part 1

, 11 Jun 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
  Data validation is very 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. So, today I am going to talk about Data Validation in Silverlight. By default silverlight doesn't give any visu

 

Data validation is very 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. So, today I am going to talk about Data Validation in Silverlight.

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. But its not the case. I agree with you, its misleading.

In this situation what can we do?

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. Lets start with simple application which will give us a simple basic ground for future advanced investigation on data validation.

 

Step 1 : Create a silverlight application and add the following Student class to your project

Student

Step 2 : Open the MainPage.xaml.cs code behind and modify the MainPage() constructor that should look like the following section. LayoutRoot is our grid container.

Codebehind_Initial 

Step 3 : There you go, XAML. The following section goes between UserControl tag.

InitXML

Step 4 : Run the application and type any string in the age filed and then try to move your cursor to other control. As expected internal validation has happened by rejecting the invalid input with no visual feedback. But we want visual feedback, lets see what can be done to achieve this “Visual feedback” or “error message”.  

iniOutput

Step 5 : ValidatesOnExceptions is the very first step for implementing all types of validation.

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
  • Type conversions failure.
  • When there is a error in binding object's set accessor.
  • When there is an exception from validation attribute

Key points to remember:

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

Now look at the modified XAML for the text boxes:

XML_Mode_Fisrt_Flag

Step 6 : Run the application and type any string in the age filed and try to move your cursor to other control. This is like magic, now I can see the visual feedback from Silverlight app and this is about the wrong data type. But that’s not enough for me, I want to put a range validation(0 to 100) for the Age field. Don’t get bored, you might be wondering why Mr Sumon is proceeding slowly? Mate, that’s how I proceed. Lets move on …..

Output_Type_Con 

Step 7 : Now its time to modify the existing Student Class. Modify the Age property setter.

 Student_setter

Step 8 : Run the application, at this stage the Age field is able to handle two types of validation (Invalid data type and Range validation). Now that we are clear on that, I am hungry for more adventure, just keep following me.

Output_0_100

What I want now is that when there is an invalid input in the Age field, I want the textbox to have yellow background and also showing the error message via tooltip. I am just showing different ways but its up to you guys to drive your imagination.

Step 9 :

NotifyonValidationError = True

NotifyonValidationError = True, this makes the binding engine to raise the BindingValidationError event during the exception. This is a routed event which could be handled by the target control or by the parent container(more realistic). Again modify the XAML for the textboxes

XML_Notify

So, I attached BindingValidationError event to the Grid container. The handler at the parent or container level could conceivably perform validation on multiple child elements.

 BindingValidationError_declare

Step 10 : Up to this point, we are having relative visual error feedback but we want more control! In BindingValidationError handler we can specify more validation actions. In our case wanted actions are, making the background yellow and showing error message using the tooltip for the guilty control.

BindingValidationError_event

Step 11 : I can't wait to run the app. There you go!

Tooltip

 

I am happy that individual control is showing the related error messages and doing extra activities. I got another idea, it would to nice if I could show all the error messages in one place in a summary format. Does this ring a bell? Yes, we can achieve this through ValidationSummary control in Silverlight.

Step 12 :

ValidationSummary

Namespace:  System.Windows.Controls
Assembly:  System.Windows.Controls.Data.Input (in System.Windows.Controls.Data.Input.dll)

Using ValidationSummary control we can display a consolidated list of validation errors. By default, the control displays error for its parent container control. To specify a different container we have to set the Target property. Target property is null by default.

Quick steps:

  • Add a reference to System.Windows.Controls.Data.Input
  • Declare the namespace in the XAML markup.
  • Finally insert the ValidationSummary control tag.

ValidationSummary_Names_Ctl

Step 13 : Running the app should give you the following one.

ValidationSummary_Box

 

Validation for the textbox happens when it loses focus, if the data is valid it gets reflected on data source otherwise gets rejected which is a default behaviour. But I want data propagation and validation to happen only when I click the save button, not when textbox looses focus . That means I have to change the default behaviour. This could be done using UpdateSourceTrigger property of the Binding object.

Step 14 :

UpdateSourceTrigger

UpdateSourceTrigger accepts two values:

  • Default
  • 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.

 

Updatesource_xml

 

Step 15 : 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.  

save_button_code

This is a multipart article and I want to take a break.  My next articles will be based on following topics:

  • Data Annotation
  • Validation with IDataErrorInfo and INotifyDataErrorInfo (This is new to Silverlight 4)

Can't wait to start the second part of this article.

Happy Coding.
Sumon Barua

Download: Source

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sumon Barua
Software Developer (Senior) Lavender
Australia Australia
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 1000705530-May-13 20:44 
GeneralMy vote of 5 PinmemberSavalia Manoj M25-Mar-13 3:55 
GeneralDamn Impressive Article PinmemberElegantly Wasted15-Dec-12 18:30 
QuestionHow we handle this type of validation in DataGrid in Silverlight Pinmemberpramodmca063-Dec-12 1:50 
GeneralVery Nice Tutorial PinmemberAshwini K Singh28-Aug-12 9:16 
Questionthanks PinmemberMember 905341210-Aug-12 1:29 
GeneralImage Download from Database in WCF Pinmembersrikanthkoyada23-Jul-12 20:03 
QuestionImage Download from Database in WCF Pinmembersrikanthkoyada23-Jul-12 20:01 
QuestionImages PinmemberGraham Cottle29-May-12 22:19 
QuestionNext articles Pinmembermmahajan921-May-12 4:00 
Generalmy vote of 5 PinmemberUday P.Singh7-Dec-11 20:18 
Questionnice but.? [modified] Pinmembermehrnush.b6-Dec-11 20:52 
QuestionThank You PinmemberMember 255944617-Nov-11 4:04 
Questiongood work Pinmemberseher.gull27-Sep-11 1:48 
GeneralGood work. PinmemberAbhishek-Tiwari21-Sep-11 0:51 
Questionnice "but" Pinmemberttphp9-Jul-11 0:09 
GeneralIt's me Sujan PinmemberSujan Barua27-Jun-11 22:58 
GeneralValidation question PinmemberMMRR23-May-11 6:10 
GeneralRe: Validation question PinmemberC84627-Oct-11 10:25 
GeneralRe: Validation question PinmemberBlaiseBraye20-Oct-11 6:47 
Generallocalization of summary header question PinmemberSrečo Vengar24-Feb-11 0:50 
GeneralVery good article PinmemberSaty997-Jan-11 10:39 
GeneralMy vote of 5 PinmemberEnrique Albert20-Dec-10 16:25 
GeneralGood Artical But i need help PinmemberGurvinder Gurvinder10-Nov-10 22:57 
Generalgood aricle Pinmemberumair guru10-Nov-10 17:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 11 Jun 2010
Article Copyright 2010 by Sumon Barua
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid