Andrej Tozon's blog

In the Attic

NAVIGATION - SEARCH

Silverlight LOB: Validation (#1)

When taking about data validation in applications, I usually describe the validation as the five-stage process or, put differently, five lines of defense against invalid data. In this post, I’ll write about the first line of defense – preventing the user entering the wrong data.

1. Preventing invalid input

This one’s logical, really. A user enters the data through input fields on some kind of input form, so naturally this would be the best place to put our first line of defense.

The first line of defense is about preventing user to enter invalid data into input fields. This doesn’t mean that if done proper and thorough, we wouldn’t need other places to check the data; it’s just the best place to filter out majority of faulty input that can happen during manual data entry. The goal here is to catch as many invalid data as possible, as soon as possible. This wouldn’t result only in better application responsiveness (no unnecessary trips to the server), the immediate feedback of invalid entry will provide a better user experience, possibly even educate the user to learn from her mistakes.

So, what are we talking about here?

A simple TextBox might not be the best solution for entering only numeric data. Seeing the TextBox on the input form, the user might expect she can enter anything she likes into the box, even if the label, put close by the input box, is saying to her: “Enter your age”. A kind of a NumericUpDown control visually gives user a much better idea of what should go into that box, plus she gets an option of manipulating that value; in this case, it’s adjusting the value with the Up and Down keys. In Windows Forms, for example, I liked to use a TextBox with a calculator dropdown for entering decimal data. Masked input boxes also work well, when you want the user to enter the data in a specific format.

If you don’t want to provide any visual clues that only numeric data should be entered in the input field and go for the standard TextBox, it’s very much recommended to handle the input for yourself and only allow numeric keys through. This is usually done by hooking into KeyDown event – either in codebehind class, or even better – with a custom TextBox behavior.

Yet another good example of filtering the data input to the underlying data type, is the DatePicker control. You can usually set the range of valid dates that can be selected and control whether or not date entry is required. With Silverlight DatePicker, it appears that date entry is always optional, even if bound to a non-nullable DateTime data type. Tabbing out of the DatePicker will leave the input box empty, but the bound property will still contain the old value. Hooking into DateValidationError or BindingValidationError event wouldn’t help so I tried to handle this case by manipulating the Selected date in the SelectedDateChanged event. Instead of doing it in the codebehind class, I created the following behavior:

public class RequiredDatePickerBehavior : Behavior<DatePicker>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectedDateChanged += OnSelectedDateChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.SelectedDateChanged -= OnSelectedDateChanged;
    }

    private void OnSelectedDateChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count == 0 && e.RemovedItems.Count > 0)
        {
            AssociatedObject.SelectedDate = (DateTime)e.RemovedItems[0];
        }
    }
}

… which can be used as:

<controls:DatePicker SelectedDate="{Binding BirthDate, Mode=TwoWay}"
                     Grid.Row="1" Grid.Column="1">
    <i:Interaction.Behaviors>
        <local:RequiredDatePickerBehavior />
    </i:Interaction.Behaviors>
</controls:DatePicker>

Attaching this behavior to the DatePicker will revert the date to the last valid value in case of deleting the text from the input box and thus making the DatePicker non-nullable.

Behaviors in general are a great way to extend an existing type (or types) of control and can be used for a variety of things. In this post I’ve shown a way to enhance the Silverlight DatePicker control to prevent entering empty values in cases when date is required. Remember next time you’ll find yourself coding KeyDown or similar control event handler in page’s codebehind class: consider writing a behavior!

To be continued…

Shout it