WPF: Check if there are validation errors

I worked on a wpf window containing some controls that were required and that validated the format of the entered data. Once the user pressed a button I wanted to check if there was any validation error and notify the user with an error message. This is how to do it:

Helper class:

namespace WPFValidation {
    static class WPFValidationExtension {
        public static bool IsValid(this DependencyObject instance) {
            return !Validation.GetHasError(instance) &&
                   LogicalTreeHelper.GetChildren(instance).OfType().All(child => child.IsValid());
        }
    }
}

Code of the button:

        private void BtnGenerateClick(object sender, RoutedEventArgs e) {
            if (!FieldHolder.IsValid()) {
                MessageBox.Show("Please fix the fields that have a red border first!", "Fix red fields", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            _viewModel.ExecuteSomeAction();
        }

The code above assumes that there is a Container (for example a stack panel) containing all fields that need to be validated whose name is FieldHolder

Source: stackoverflow.com/questions/127477/detecting-wpf-validation-errors

Leave a comment

Your email address will not be published. Required fields are marked *