Data validation is the process of ensuring the data a user has entered is valid. For example, if you prompt a user for a phone number you would want to validate the string consist of only numeric values and that it matches a specific format such as (555) 555-5555.
Using Silverlight you can hook up controls to a class that will be used to programmatically verify the data being entered. Controls can bind to any given property in that class where the data validation will be done.
To demonstrate this I created a class called “UserProfile” that is used to store data about a user including their phone number. For the demo purpose I will only be doing data validation against the phone number. I use a regular expression to verify we have a string of numbers in a given format. The class throws an exception which is used by Silverlight to display a message to the user that the format is not correct (see demo below).
public classUserProfile
{
private string _phoneNumber = String.Empty;
public string Name { get; set; }
public string Address { get; set; }
public string PhoneNumber
{
get { return _phoneNumber; }
set
{
value = value.Replace(" ", "");
Regex phoneExp = new Regex(@"^\(\d{3}\)\d{3}-\d{4}$");
if (false == phoneExp.Match(value).Success)
{
throw new Exception("Phone number must be in the format:\n (555) 555-5555");
}
}
}
}
In your XAML to hook up your controls to do data validation with this class you simply need to declare a DataContext section that references this class. Example:
<Grid x:Name="LayoutRoot" >
<Grid.DataContext>
<local:UserProfile />
</Grid.DataContext>
Next, bind your controls properties in this class. The properties in the class should throw an exception with an error message if they are not valid. In the code below I am binding the TextBox to the PhoneNumber property of the UserProfile class.
<TextBlock x:Name="PhoneNumber"Text="Enter your phone number:"/>
<TextBox Text="{BindingPhoneNumber,Mode=TwoWay, ValidatesOnExceptions=True}"/>
In the demo below, type in an invalid phone number. As soon as the control loses focus data validation is performed. Hit the <tab> key to see this happen once you enter an invalid phone number. The result will be a red border around your TextBox. Click the arrow in the upper-right corner of the control to see the error message.
Source: Tip22_DataValidation.zip
Thank you,
–Mike






