Validation in Silverlight 3


Introduction

In this article we will see how we can use RegEx Validation in Silverlight.

Creating Silverlight Project

Fire up Visual Studio 2008 and create a new Silverlight 3 Project. Name it as RegExValidation.

1.gif
 
The sample application will contain two TextBox. In one TextBox we will input the RegEx Expression and in the other we will input a value matching to it. If both matches display success message if not display error message.

Remember we can only validate the RegEx expression with a matching value only. We cannot validate a RegEx expression (till now).

Create two TextBoxes with a Button and a Status TextBlock.

2.gif
 
You need to use the following Namespace to use RegEx.

 

using System.Text.RegularExpressions;

In the Button click event check whether the value matches.

private
void btnCheck_Click(object sender, RoutedEventArgs e)
{
    string pattern = txtRegEx.Text;
    string content = txtDefaultValue.Text;
    if (Regex.IsMatch(content,pattern))
    {
        txtStatus.Text = "Regular Expression and Default Value are Matched";
    }
    else
    {
        txtStatus.Text = "Regular Expression or Default Value is Wrong";
    }
}

That's it. It's so simple. Now if you run the application, you can check whether your RegEx expression is matching to default value or not.

3.gif
4.gif
 
 
Hope this article helps.


Similar Articles