21
Oct
10

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}" 
                     BindingValidationError="ContentPanel_BindingValidationError">
                <TextBox.InputScope>
                    <InputScope>
                        <InputScope.Names>
                            <InputScopeName>Default</InputScopeName>
                        </InputScope.Names>
                    </InputScope>
                </TextBox.InputScope>
            </TextBox>
        </Grid>

 

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; }
            set
            {
                if (_myText != value)
                {
                    if (value.Contains("."))
                    {
                        throw new Exception("Cannot contain '.'");
                    }

                    _myText = value;
                    OnPropertyChanged("MyText");
                }
            }
        }

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            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 Responses to “Simple textbox validation wp7”


  1. 1 M.Bi.
    October 27, 2010 at 10:57 am

    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. 2 M.Bi.
    October 27, 2010 at 12:33 pm

    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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.