user3692104
user3692104

Reputation: 189

How to check ValidationResults on button click

I have the a bunch of textboxes all with data validation as follows:

xaml

<TextBox>
    <TextBox.Text>
        <Binding Path="Name" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:Validation2/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

c#

public class Validation2 : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        double result;
        return double.TryParse(value.ToString(), out result) == true ? new ValidationResult(true, null) : new ValidationResult(false, "error");
    }
}

This works nicely, whenever I put anything but a number in the textboxes an error pops up. Now I have a button to send the "form", I'd like the button to check if there were any validation errors before doing anything. How would I go about doing that.

Upvotes: 0

Views: 461

Answers (1)

Sinatr
Sinatr

Reputation: 21989

Validation occurs before applying new value to source property. In your case - when you change property. In wpf there are also few more cases, but there is no OnFormClosing or similar. It's by design: control property may be bound to other control property (or several controls bound to same property), so validation occurs at latest when you change focus.

If you don't have cross-bindings, one property is bound to only one control, then you may utilize UpdateSourceTrigger.Explicit - call UpdateSource() for each binding when form is about to be closed.

Other solution would be to don't display errors as popups. Error status could be a red border or ! icon near.

I myself don't use validation mechanism at all. Instead, I have self-validating controls, to example, TextBox with property IsDouble to enable automatic validation for double values and property GetDouble, to parse value. I like more to validate everything at the end, while displaying actual status if validation will be ok or not to the user (red border, flashing caption, etc. per control).

Upvotes: 0

Related Questions