Silverlight TextBox Numeric Validation

While conducting a Silverlight training at one of my clients who was migrating from ASP.NET AJAX to Silverlight 4.0. While discussing input validations, my students raised a question that in AJAX we have the FilteredTextExtender using which the TextBoxes can be restricted to accept only Character or numeric data. Can we have a similar capability in Silverlight 4.0 too?

On a side note, if you are a Silverlight developer, here’s a must read article - Microsoft Silverlight 4 Tutorials You Must Read

Although we have IDataErrorInfo interface for input data validation in Silverlight, it provides us validation error when the user enters the data and leaves the textbox. However the requirement we are talking about is when the user enters any data in the textbox, it should be automatically validated. This article contains the solution to this requirement.

In this article I have used the ‘System.Windows.Interactivity’, namespace which is available in the following path:


c:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0     \Libraries\System.Windows.Interactivity.dll


Step 1: Open VS2010 and create a new Silverlight project, name it as ‘SL4_Restricting_UserInputs’. In this project add the library file I just shared. This dll is used to set the TextChange behavior for the TextBox.

Step 2: In the project, add a class and name it as ‘TextBoxTextChangedUpdateBehavior’:


silverlight-textbox-change


Note: In the class file, you need to use the System.Windows.Interactivity as shown below:

using System.Windows.Interactivity;


The above class defines the custom textchange behavior for the textbox. This is done as the input to the textbox must be validated the moment the end-user enters the data in the textbox. The Behavior<T> class is used to define the custom behavior for the Silverlight element by attaching the UI Element object to the AssociatedObject and then register the event, for which the Behavior is to be customized.


Step 3: Add the following class to the Project. This class acts as a Data class for the UI TextBoxes. It implements ‘INotifyPropertyCanged’ interface. This is because the public properties exposed by the class are bound with the UI. So when the UI changes, the property will update itself and perform the validation. The code for doing this is as shown below:


/// <summary>
/// The class containing the Validation logic for Numeric and Character data
/// </summary>
public class ValidateInput :  INotifyPropertyChanged
{
string _Numeric;

public string Numeric
{
    get { return _Numeric; }
    set
    {
        string ValueEntered = value.ToString();
        if (ValueEntered.Length != 0)
        {
            //Check for the ASCII for the Numeric
            foreach (char c in ValueEntered)
            {
                if (c >= 48 && c <= 57)
                {
                    _Numeric = value;
                    ErrorMessageNumeric = "";
                    continue;
                }
                else
                {
                    ErrorMessageNumeric = "Sorry!!Please enter only Numeric Values Here";
                    break;
                }
            }
        }
        else
        {
            ErrorMessageNumeric = "";
        }
        OnPropertyChanged("Numeric");
    }
}
string _Character;

public string Character
{
    get { return _Character; }
    set
    {
        string ValueEntered = value.ToString();
        if (ValueEntered.Length != 0)
        {
            //Check for the ASCII for the Character Data
            foreach (char c in ValueEntered)
            {
                if ((c >= 65 && c <= 90)||(c>=97 && c<=122))
                {
                    _Character = value;
                    ErrorMessageCharacter = "";
                    continue;
                }
                else
                {
                    ErrorMessageCharacter = "Sorry!!Please enter only Character Values Here";
                    break;
                }
            }
        }
        else
        {
            ErrorMessageCharacter = "";
        }
        OnPropertyChanged("Numeric");
    }
}
string _ErrorMessageNumeric;

public string ErrorMessageNumeric
{
    get { return _ErrorMessageNumeric; }
    set
    {
        _ErrorMessageNumeric = value;
        OnPropertyChanged("ErrorMessageNumeric");
    }
}

string _ErrorMessageCharacter;
public string ErrorMessageCharacter
{
    get { return _ErrorMessageCharacter; }
    set
    {
        _ErrorMessageCharacter = value;
        OnPropertyChanged("ErrorMessageCharacter");
    }
}

public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string pName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this,new PropertyChangedEventArgs (pName));
    }
}
    
}



Step 4: Open MainPage.Xaml and add the XAML shown below. This will define an instance of the ValidateInput class created above in the UserControl.Resources. The public properties from the class are bound with the Textboxes. The UI also contains TextBlock which are bound with the properties ErrorMessageNumeric and ErrorMessageCharacter for displaying the error accordingly. Every TextBox is assigned with the Custom Behavior by registering System.Windows.Interactivity namespace in XAML. The XAML code is as below:

silverlight-textbox-validation



Task 5: Run the application and enter alphabets in the textboxes which expect numeric data. The validation message will be displayed as shown below:

clip_image001

Conclusion: While developing Line-of-Business applications using Silverlight, we often come across forms which contain fields like EmpName, DeptName etc. For such fields, we need character data whereas for entries like Salary etc, we require Numeric Data. So using the validation mechanism shown in this article, we are able to provide the user with an instant message when he/she enters wrong data.

Download the source code




About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

No comments: