Detecting WPF Validation Errors

Viewed 66921

In WPF you can setup validation based on errors thrown in your Data Layer during Data Binding using the ExceptionValidationRule or DataErrorValidationRule.

Suppose you had a bunch of controls set up this way and you had a Save button. When the user clicks the Save button, you need to make sure there are no validation errors before proceeding with the save. If there are validation errors, you want to holler at them.

In WPF, how do you find out if any of your Data Bound controls have validation errors set?

11 Answers

This post was extremely helpful. Thanks to all who contributed. Here is a LINQ version that you will either love or hate.

private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = IsValid(sender as DependencyObject);
}

private bool IsValid(DependencyObject obj)
{
    // The dependency object is valid if it has no errors and all
    // of its children (that are dependency objects) are error-free.
    return !Validation.GetHasError(obj) &&
    LogicalTreeHelper.GetChildren(obj)
    .OfType<DependencyObject>()
    .All(IsValid);
}

The following code (from Programming WPF book by Chris Sell & Ian Griffiths) validates all binding rules on a dependency object and its children:

public static class Validator
{

    public static bool IsValid(DependencyObject parent)
    {
        // Validate all the bindings on the parent
        bool valid = true;
        LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();
        while (localValues.MoveNext())
        {
            LocalValueEntry entry = localValues.Current;
            if (BindingOperations.IsDataBound(parent, entry.Property))
            {
                Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                foreach (ValidationRule rule in binding.ValidationRules)
                {
                    ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);
                    if (!result.IsValid)
                    {
                        BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                        System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));
                        valid = false;
                    }
                }
            }
        }

        // Validate all the bindings on the children
        for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (!IsValid(child)) { valid = false; }
        }

        return valid;
    }

}

You can call this in your save button click event handler like this in your page/window

private void saveButton_Click(object sender, RoutedEventArgs e)
{

  if (Validator.IsValid(this)) // is valid
   {

    ....
   }
}

The posted code did not work for me when using a ListBox. I rewrote it and now it works:

public static bool IsValid(DependencyObject parent)
{
    if (Validation.GetHasError(parent))
        return false;

    // Validate all the bindings on the children
    for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        if (!IsValid(child)) { return false; }
    }

    return true;
}

You can iterate over all your controls tree recursively and check the attached property Validation.HasErrorProperty, then focus on the first one you find in it.

you can also use many already-written solutions you can check this thread for an example and more information

In answer form aogan, instead of explicitly iterate through validation rules, better just invoke expression.UpdateSource():

if (BindingOperations.IsDataBound(parent, entry.Property))
{
    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
    if (binding.ValidationRules.Count > 0)
    {
        BindingExpression expression 
            = BindingOperations.GetBindingExpression(parent, entry.Property);
        expression.UpdateSource();

        if (expression.HasError) valid = false;
    }
}

I am using a DataGrid, and the normal code above did not find errors until the DataGrid itself lost focus. Even with the code below, it still doesn't "see" an error until the row loses focus, but that's at least better than waiting until the grid loses focus.

This version also tracks all errors in a string list. Most of the other version in this post do not do that, so they can stop on the first error.

public static List<string> Errors { get; set; } = new();

public static bool IsValid(this DependencyObject parent)
{
    Errors.Clear();

    return IsValidInternal(parent);
}

private static bool IsValidInternal(DependencyObject parent)
{
    // Validate all the bindings on this instance
    bool valid = true;

    if (Validation.GetHasError(parent) ||
        GetRowsHasError(parent))
    {
        valid = false;

        /*
         * Find the error message and log it in the Errors list.
         */
        foreach (var error in Validation.GetErrors(parent))
        {
            if (error.ErrorContent is string errorMessage)
            {
                Errors.Add(errorMessage);
            }
            else
            {
                if (parent is Control control)
                {
                    Errors.Add($"<unknow error> on field `{control.Name}`");
                }
                else
                {
                    Errors.Add("<unknow error>");
                }
            }
        }
    }

    // Validate all the bindings on the children
    for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (IsValidInternal(child) == false)
        {
            valid = false;
        }
    }

    return valid;
}

private static bool GetRowsHasError(DependencyObject parent)
{
    DataGridRow dataGridRow;

    if (parent is not DataGrid dataGrid)
    {
        /*
         * This is not a DataGrid, so return and say we do not have an error.
         * Errors for this object will be checked by the normal check instead.
         */
        return false;
    }

    foreach (var item in dataGrid.Items)
    {
        /*
         * Not sure why, but under some conditions I was returned a null dataGridRow
         * so I had to test for it.
         */
        dataGridRow = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(item);
        if (dataGridRow != null &&
            Validation.GetHasError(dataGridRow))
        {
            return true;
        }
    }
    return false;
}
Related