Windows Phone 7

Simple textbox validation wp7

Since wp7 is based on Silverlight 3 then input validation can be done (love or loathe it) via exceptions. Here’s a simple example…

        <Grid x:Name="ContentPanel" Grid.Row="1">
            <Border x:Name="errorBorder" Background="Red" Opacity="0"></Border>
            <TextBox Margin="8" 
                     Text="{Binding MyText, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 


Note that the Textbox is bound to a text property and NotifyOnValidationError and ValidatesOnExceptions properties have been set to true. Also, the binding will be triggered when the TextBox loses focus. Setting NotifyOnValdationError means that my event handler for BindingValidationError event will be called when a validation error is detected. Following from that, a validation error will be detected when my bound property setter (for ‘MyText’) throws an exception. Here’s the code for that….


   public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        private string _myText;

        public string MyText
            get { return _myText; }
                if (_myText != value)
                    if (value.Contains("."))
                        throw new Exception("Cannot contain '.'");

                    _myText = value;

        // Constructor
        public MainPage()
            DataContext = this;

        private void ContentPanel_BindingValidationError(object sender, ValidationErrorEventArgs e)
            errorBorder.Opacity = e.Action == ValidationErrorEventAction.Removed ? 0 : 100;



I haven’t been very creative with the visuals here…

Note that I have placed all of this code in the code-behind purely for convenience – I would usually implement this with a view model.

3 thoughts on “Simple textbox validation wp7

  1. Very nice example. I have tried to apply this to my application but unfortunatly it doesnt work: the exception thrown from the ViewModel isn’t caught by the Data Binding even though NotifyOnValidationError and ValidatesOnExceptions are set to True. Any hints?

  2. To answer myself:

    My problem was that i was changing the data directly in the underlying viewmodel. This triggered the exception of course but at the same time skipped over the databinding.
    When i change the content of the input control instead and let the databinding try to updated the viewmodel the exception is properly caught by the databinding.

Leave a Reply

Your email address will not be published. Required fields are marked *