Silverlight Tips provides simple and useful tutorials and tips with real life examples, live demos and sample codes to download.
About authors:
Damon Serji
Damon Serji,
Silverlight developer working at Metia in London.
Gavin Wignall
Gavin Wignall,
Interactive Design Lead, working in design for over 10 years, the last 3 being in Silverlight.
Allan Muller
Allan Muller,
Developer, working on various types of Silverlight and WCF projects.
Get Microsoft Silverlight

The built-in validation in Silverlight 3.0 is a great new feature that can be used on essential Silverlight controls such as TextBox. Using this feature, it is possible to nicely display an error message and highlight the TextBox that has bad value.

In this post I will only cover validating data in TextBox controls, which are simply used in most forms to receive basic information such as Name, Surname and Email address. The completed and working version of this project can be downloaded from CodePlex from here. I will explain and provide solution on how to validate ComboBox, Radio Button controls or etc in another post soon, so please keep yourself updated on new posts here.

1. Create a basic form with a few TextBox controls in the xaml

2. Create a class, call it CustomValidation
Add the following code to your CustomValidation class:

private string message;
public CustomValidation(string message)
{
    this.message = message;
}
public bool ShowErrorMessage
{
    get;
    set;
}
public object ValidationError
{
    get
    {
        return null;
    }
    set
    {
        if (ShowErrorMessage)
        {
            throw new ValidationException(message);
        }
    }
}

3. Create an Extension class (Extensions)
To understand what is an Extension class and for more information about them visit my tutorial post “Extension methods in Silverlight and C#”.

In brief: Extensions will be your Extension class to extend any object of type FrameworkElement like TextBox controls within your application framework. It means you can use the public methods within this class as a “built-in” method for your TextBox.

Create a static public method and call it SetValidation. This method receives an instance of a FrameWorkElement and a string value, and returns nothing:

public static void SetValidation(this FrameworkElement frameworkElement, string message)
{
    CustomValidation customValidation = new CustomValidation(message);
    Binding binding = new Binding("ValidationError")
    {
        Mode = System.Windows.Data.BindingMode.TwoWay,
        NotifyOnValidationError = true,
        ValidatesOnExceptions = true,
        Source = customValidation
    };
    frameworkElement.SetBinding(Control.TagProperty, binding);
}

CustomValidation is the class we defined earlier.

"Binding" is a class in System.Windows.Data assembly which gets or sets a value that indicates whether to raise the error attached event on the bound object.

What are we doing? Here we have a CustomValidation class that has one property ("ShowErrorMessage") and one public methods ("ValidationError"). "ValidationError" is our source binding object and what we want to be able to do in the future is to bind our frameworkElement, which is a TextBox, to ValidationError. We are in simple words binding the CustomValidation class to our TextBox once we call this method on our TextBox.

For more information on Binding and BindingExpression visi msdn article here.

Create another two methods for displaying validation error and also for clearing validation error when the error was corrected:

public static void RaiseValidationError(this FrameworkElement frameworkElement)
{
    BindingExpression b =
    frameworkElement.GetBindingExpression(Control.TagProperty);
    if (b != null)
    {
        ((CustomValidation)b.DataItem).ShowErrorMessage = true;
        b.UpdateSource();
    }
}

public static void ClearValidationError(this FrameworkElement frameworkElement)
{
    BindingExpression b =
    frameworkElement.GetBindingExpression(Control.TagProperty);
    if (b != null)
    {
        ((CustomValidation)b.DataItem).ShowErrorMessage = false;
        b.UpdateSource();
    }
}

By creating a new BindingExpression you will be creating an instance of your binding so you can control the properties and public methods of your binding source/target. In above case, we are casting the BindingExpression.DataItem as CustomValidation. This enables us to access the properties of this class, "ShowErrorMessage" in this case.

4. RaiseValidationError() and ClearValidationError()
So now we have our TextBox, a method in our Extension class to bind the TextBox to our CustomValidation class and passes our error message, and a method in our Extension class that fires throw new ValidationException(message); from the CustomValidation class.

All we need to do now is to check if a specific TextBox is valid or not. If the TextBox was not valid we can simply use the RaiseValidationError() and ClearValidationError() methods, which should now be available from the intellisense in Visual Studio, to throw the validation exception and display a suitable error message and we do that by following code when the submit button was pressed:

Name.ClearValidationError();
bool isFormValid = true;
if (Name.Text == "")
{
    Name.SetValidation("Please enter your name");
    Name.RaiseValidationError();
    isFormValid = false;
}

use isFormValid variable to check if you have to submit the form or not. The Name.ClearValidationError() makes sure you clear the form everytime you press submit, so if the form was valid the error message had already been cleaned.

I have some extra validation extensions on this project and have organised the code in different class files. Download the project from here.

Posted by Damon Serji on 8. October 2009 19:24 under: Advance, Intermediate
 with 9 Comments

Comments

kevin:

Hi,

This is a great article. I have a question for you. Could I use customize validation to Datagrid control?
Because I have several data members in server side, I try to validate those data in client side. I cannot validata those data by WCF. I would like move  validation to client side now.

Posted 10/3/2009 3:42:16 PM

Damon:

Hi Kevin,

Thanks for your comment and welcome to Silverlight Tips.

So if I understood correctly, you are binding some data to your DataGrid control, and you want them to be validated before the form is submitted?

I haven't done this before, but as far as I know you can validate your data model using RIA services. That means your data will automatically be validated when you try to submit and before it is passed to your database.

I will be posting a new article in continues to data validation to demonstrate validating data model in silverlight. You can keep yourself updated about new posts from my twitter account here: http://twitter.com/silverlighttips

Posted 10/8/2009 1:46:28 PM

Siva:

Great Post!

Posted 11/8/2009 12:21:11 AM

Hi Damon,

Great article man! was very useful.

I have one question.. I am also using a "validation summary" control and therefore all validation messages i raise also get included in that validation summary.

This is cool, but in the validation summary the messag looks something like this:
ValidationError Please enter a value

The "Please enter a value" is the message i send in and thats fine.. BUT the ValidationError seems to be included automatically. Usaully when you bind to a property you can set the display attribute to a more friendlier message and that would appear, but in this situation i dont know how to show a more "friendlier" message than "ValidationError"??

Any tips of how to do this?

tnx,

Posted 11/26/2009 2:39:44 PM

Stephen Clarke:

Hi Damon,

Thanks for a very useful article, this is exactly what I'm looking for.  I want to manually trigger the red validation ui without using the inbuilt validation mechanism (which doesn't work well with the IEditableObject interface that I'm using for undoable editing).

This works great with the TextBox.  You mentioned that a solution is also available for ComboBox, but you didn't post it and I can't work it out, it seems quite different to your TextBox method.  

Could you post your ideas for ComboBox manual validation, I'm pulling my hair out over this!

Posted 12/20/2009 1:10:40 PM

Apoorva :

Hi Damon,

U saved me from comitting suicide Smile (kidding)
its  a very simple, useful way to do the validations............. thnkx a ton..

- Regards
Apoorva

Posted 12/26/2009 7:44:55 AM

leon:

I really struggle to see the point in doing it this way.
SL has great built in validation, why don't use it instead?

Posted 2/11/2010 3:22:14 PM

j:

Hi,
thanks for the post. It could be useful for me but I have a small problem. My textbox is already bound to some property in an object. So binding to the CustomValidartor will override my previous binding. (My object is generate from a web service reference.
Ideally, using a metadata class with a MetadataType property would be nice, but unfortunately it is not supported in Silverlight.

Any idea of custom validation without loosing the binding I already have?

Thanks
J

Posted 4/13/2010 9:49:12 PM

Parth:

Hi a very helpful article for silverlight developer.
i used the same thing in my application but it is giving an exeption error "ValidationException was unhandled by usercode" in the class customValidation. can u please help me how to resolve it..

Posted 5/12/2010 11:52:30 AM

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview