post icon

Silverlight Tip of the Day #22 – Data Validation

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.

[silverlight: Tip22_DataValidation.xap]

Thank you,
–Mike

8 Comments

Leave a comment
  1. Mark Stevens
    19. May, 2010 at 11:50 am #

    Lime green on white in the RSS feed – great colour combination !

  2. denny
    19. May, 2010 at 3:49 pm #

    Mike, please take a look at this and see if you can help me

    http://forums.silverlight.net/forums/t/182372.aspx

    Thanks!

  3. Snowman
    19. May, 2010 at 4:56 pm #

    Mark- I’ll work on fixing that, thanks for pointing it out.

    Denny – I’ll see if i can find time tomorrow to check it out. Thanks.

  4. denny
    20. May, 2010 at 7:00 am #

    Thanks!
    email me if you want more detail on what i am trying to do etc…
    I know i am just missing some details but which interface i need to hookup and which events is where i am lost.

  5. leifre
    25. May, 2010 at 11:36 pm #

    You should probably use a ValidationException instead of a generic Exception as that is what it is there for.

    If you are using Silverlight 4, you really shouldnt be using exceptions at all actually. It is still valid and you can do it but the preferred way is to use the IDataErrorInfo or INotifyDataErrorInfo

  6. Snowman
    26. May, 2010 at 7:06 am #

    Thanks Lifre for the info, i’ll look into IDataErrorInfo and INotifyDataErrorInfo

  7. D.Vasanthnidhi
    06. Jul, 2011 at 1:29 am #

    l have a doubt in viewmodel part of MVVM in Silverlight.Consider c= a+b
    we are getting and setting for

    a
    getset
    b
    getset
    c
    getset

    and raise propery changed event for a ,b,c.

    a
    getset
    raisproperychanged(“a”)
    b
    getset
    raisproperychanged(“b”)

    c
    getset
    raisproperychanged(“c”)

    i understand we raise properychanged method for each field
    but why do we raiproperychangedevent method for c in a and b

    a
    getset
    raisproperychanged(“a”)
    raisproperychanged(“c”)-why c is raised in a

    b
    getset
    raisproperychanged(“b”)
    raisproperychanged(“c”)

    c
    getset
    raisproperychanged(“c”)

    with regards,
    D.Vasanthnidhi

Trackbacks/Pingbacks

  1. Silverlight Tip of the day #25 – Detecting Validation Errors on Submit | Silverlight Tips of the Day - 28. May, 2010

    [...] When you are about to submit a form, click OK on a dialog, etc. it’s a good idea to first verify if any of your controls have data validation errors associated with them. To learn how to hook up your controls to data validation please review Tip of the Day #22. [...]