wpfnullvalidationrulesvalidationrule

Can you safely return null from a custom ValidationRule, to signify no validation performed?


I am implementing a custom ValidationRule for WPF DataBinding. To do this, I just inherit from ValidationRule and implement one or more of a few abstract or virtual methods. This is the method I am implementing:

public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo, System.Windows.Data.BindingExpressionBase owner)

The ValidationResult object I am returning must either have true or false for the IsValid property. This logically seems to me to be missing the third option Unknown or Undetermined. In some cases, a validator may not apply.

So what should I return in these cases? Can I safely return null?


Solution

  • NO!! A validator should not return null from any overloads of the Validate method, and before you ask it should not throw exceptions either. In either of these cases your application will encounter an unhandled exception in framework code, and probably crash.

    So just accept the less than perfect semantics, and return ValidationResult.ValidResult if you want your custom validator to essentially be a no-op.

    Source: tested on .NET 4.5