Validating Textbox on Lost Focus in RIA Service, Silverlight 4


While working on my article on "Data Binding in Silverlight with RIA and Entity Framework - Part 3 (Validating Input Data)", a series of articles on RIA Services, I came across a situation where I wanted to validate my textbox control on a particular event. For e.g on LostFocous. As we know the the validation fires only when the source property value gets changed and the entity gets updated. But you might have known that the Textbox Text property gets updated on LostFocus (MSDN Link). This is the default behaviour but it does not work with RIA Service in Textbox.Baring teeth smile

And most of the time the validation on the client side needs to be triggered explicitly on our demand. For e.g refer to my StatesOfIndia Application as the user provides some value for state Name and moves on;  the validation needs to be fired. 

So to implement the validation on LostFocus of StateName textbox, follow the following steps:

Make Sure you have Implemented the validation Rule at Model Entity Member
In the Metadata file I have added Required Attribute for the statename.

image_thumb9.png

Change the UpdateSourceTrigger of Textbox
Then change the UpdateSourceTrigger property of the binding of the Textbox to explicit mode.

image_thumb10.png

Update the Source at your desired event
As I want to force an update of the data as well as fire validation on the lost focus event, I am going to get the binding expression of the control and update it's source.

  1. private void txtStateName_LostFocus(object sender, RoutedEventArgs e)
  2. {
  3. System.Windows.Data.BindingExpression bexpress = txtStateName.GetBindingExpression(TextBox.TextProperty);
  4. bexpress.UpdateSource();

  5. }

As soon as the property gets changed, the validation will fire.
That is it for now; I will soon post with a detailed article on validation. Stay Tuned Smile


Similar Articles