3

How to implement binding validation for a textbox?

<TextBox Name="textBox1" Width="50" FontSize="15"
     Validation.ErrorTemplate="{StaticResource validationTemplate}"
     Style="{StaticResource textBoxInError}"
     Grid.Row="1" Grid.Column="1" Margin="2">
    <TextBox.Text>
        <Binding Path="Age" Source="{StaticResource ods}"
         UpdateSourceTrigger="PropertyChanged" >
            <Binding.ValidationRules>
          // *** What should I write here? ***     
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

What should I write in the validation Rule?

2 Answers 2

3

The following example shows the implementation of AgeRangeRule, which inherits from ValidationRule and overrides the Validate method. The Int32.Parse() method is called on the value to make sure that it does not contain any invalid characters. The Validate method returns a ValidationResult that indicates if the value is valid based on whether an exception is caught during the parsing and whether the age value is outside of the lower and upper bounds.

public class AgeRangeRule : ValidationRule
{
    private int _min;
    private int _max;

    public AgeRangeRule()
    {
    }

    public int Min
    {
        get { return _min; }
        set { _min = value; }
    }

    public int Max
    {
        get { return _max; }
        set { _max = value; }
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        int age = 0;

        try
        {
            if (((string)value).Length > 0)
                age = Int32.Parse((String)value);
        }
        catch (Exception e)
        {
            return new ValidationResult(false, "Illegal characters or " + e.Message);
        }

        if ((age < Min) || (age > Max))
        {
            return new ValidationResult(false,
              "Please enter an age in the range: " + Min + " - " + Max + ".");
        }
        else
        {
            return new ValidationResult(true, null);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

To expand on Cornel's answer, here is the related XAML that you would use with his example code:

<TextBox Name="textBox1" Width="50" FontSize="15"
     Validation.ErrorTemplate="{StaticResource validationTemplate}"
     Style="{StaticResource textBoxInError}"
     Grid.Row="1" Grid.Column="1" Margin="2"> <TextBox.Text>
<Binding Path="Age" Source="{StaticResource ods}"
         UpdateSourceTrigger="PropertyChanged" >
  <Binding.ValidationRules>
    <c:AgeRangeRule Min="21" Max="130"/>
  </Binding.ValidationRules>
</Binding></TextBox.Text></TextBox>

So in summary, you create your custom Validation class, reference it in your XAML code, and then implement it with the necessary properties initialized.

MSDN example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.