Search code examples
c#wpfvalidationidataerrorinfo

How to determine if an user has entered an incorrect input?


I was looking this site for data validation:

http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/

And it sounds great the validation. But for example I realized you can only validate data when the input is correct, if there's a way to set a message when the input is not correct.

I.E. If I have a property Age where is an int, I want to custom the error message to display where the user wrote "a" in a textBox.

I mean, Age property must validate two things, the input will be correct and the range.


Solution

  • Assuming you are using Data-Binding, you need to validate your input with validation rules:

    <TextBox Name="tb_act_name"
                             Style="{StaticResource formTextBox}"
                             Validation.ErrorTemplate="{StaticResource validationTemplate}">
                      <TextBox.Text>
                        <Binding Path="act_name"
                                 Mode="TwoWay"
                                 UpdateSourceTrigger="PropertyChanged"
                                 ValidatesOnDataErrors="True">
                          <Binding.ValidationRules>
                            <local:fieldNullOrEmpty ErrorMessage="Enter Client Name" />
                          </Binding.ValidationRules>
                        </Binding>
                      </TextBox.Text>
                    </TextBox>
    

    You would simply add more rules in the Binding.ValidationRules section. This is quite a big subject so you may wish to check out MSDN WPF Validation for more help.

    Hope this points you in the right direction.