Kevin Berridge
Kevin Berridge

Reputation: 6303

Detecting WPF Validation Errors

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?

Upvotes: 123

Views: 73003

Answers (12)

aogan
aogan

Reputation: 2271

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
    {
        ....
    }
}

Upvotes: 50

rick
rick

Reputation: 577

Add the Validation.Error event in your datagrid with NotifyOnValidationError=True in your bindings:

MainWindow.xaml

<DataGrid x:Name="myDgv" Validation.Error="myDgv_Error">

  <DataGridTextColumn Header="SomeHeader" 
                      Width="100" 
                      Binding="{Binding Name, NotifyOnValidationError=True}"> 
  </DataGridTextColumn>
</DataGrid>

<Button x:Name="btnSave" Click="onSave_Click">Save</Button>

Then all you need to do is set the isEnabled property of the button accordingly:

MainWindow.cs

 private void myDgv_Error (object sender, System.Windows.Controls.ValidationErrorEventArgs e)
  {
    btnSave.IsEnabled = e.Action == System.Windows.Controls.ValidationErrorEventAction.Removed;
  }

ValidationErrorEventAction .Removed means the error has been removed, otherwise it was .Added.

Upvotes: 0

Jim
Jim

Reputation: 2146

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;
}

Upvotes: 0

skiba_k
skiba_k

Reputation:

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;
    }
}

Upvotes: 0

Johan Larsson
Johan Larsson

Reputation: 17600

Here is a library for form validation in WPF. Nuget package here.

Sample:

<Border BorderBrush="{Binding Path=(validationScope:Scope.HasErrors),
                              Converter={local:BoolToBrushConverter},
                              ElementName=Form}"
        BorderThickness="1">
    <StackPanel x:Name="Form" validationScope:Scope.ForInputTypes="{x:Static validationScope:InputTypeCollection.Default}">
        <TextBox Text="{Binding SomeProperty}" />
        <TextBox Text="{Binding SomeOtherProperty}" />
    </StackPanel>
</Border>

The idea is that we define a validation scope via the attached property telling it what input controls to track. Then we can do:

<ItemsControl ItemsSource="{Binding Path=(validationScope:Scope.Errors),
                                    ElementName=Form}">
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type ValidationError}">
            <TextBlock Foreground="Red"
                       Text="{Binding ErrorContent}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 2

Dean
Dean

Reputation: 1496

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);
}

Upvotes: 148

Matthias Loerke
Matthias Loerke

Reputation: 2187

In addition to the great LINQ-implementation of Dean, I had fun wrapping the code into an extension for DependencyObjects:

public static bool IsValid(this DependencyObject instance)
{
   // Validate recursivly
   return !Validation.GetHasError(instance) &&  LogicalTreeHelper.GetChildren(instance).OfType<DependencyObject>().All(child => child.IsValid());
}

This makes it extremely nice considering reuseablity.

Upvotes: 7

jbe
jbe

Reputation: 7031

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use validation in WPF and how to control the Save button when validation errors exists.

Upvotes: 0

sprite
sprite

Reputation: 3752

I would offer a small optimization.

If you do this many times over the same controls, you can add the above code to keep a list of controls that actually have validation rules. Then whenever you need to check for validity, only go over those controls, instead of the whole visual tree. This would prove to be much better if you have many such controls.

Upvotes: 2

user195268
user195268

Reputation:

Had the same problem and tried the provided solutions. A combination of H-Man2's and skiba_k's solutions worked almost fine for me, for one exception: My Window has a TabControl. And the validation rules only get evaluated for the TabItem that is currently visible. So I replaced VisualTreeHelper by LogicalTreeHelper. Now it works.

    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);
                if (binding.ValidationRules.Count > 0)
                {
                    BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                    expression.UpdateSource();

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

        // Validate all the bindings on the children
        System.Collections.IEnumerable children = LogicalTreeHelper.GetChildren(parent);
        foreach (object obj in children)
        {
            if (obj is DependencyObject)
            {
                DependencyObject child = (DependencyObject)obj;
                if (!IsValid(child)) { valid = false; }
            }
        }
        return valid;
    }

Upvotes: 16

H-Man2
H-Man2

Reputation: 3189

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;
}

Upvotes: 36

user21243
user21243

Reputation: 53

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

Upvotes: 0

Related Questions