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
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.
Step 3 : There you go, XAML. The following section goes between UserControl tag.
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”.
Step 5 : ValidatesOnExceptions is the very first step for implementing all types of validation.
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:
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 …..
Step 7 : Now its time to modify the existing Student Class. Modify the Age property 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.
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
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.
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.
Step 11 : I can't wait to run the app. There you go!
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 :
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.
- Add a reference to System.Windows.Controls.Data.Input
- Declare the namespace in the XAML markup.
- Finally insert the ValidationSummary control tag.
Step 13 : Running the app should give you the following one.
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 accepts two values:
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.
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.
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.