Practical .NET

Incremental Validation in WPF

WPF provides the richest environment for developers to incorporate standalone validation classes into their user interfaces—and for business object developers to support an application's user interface.

How do you ensure that developers using your business objects also incorporate the necessary validation code to guarantee that only good data is passed to your class' property? I've looked at the three interfaces that allow you to incorporate validation code into your class while integrating with an application's user interface, and Data Annotations which allow you to separate your validation code from your class. WPF includes another option that allows developers to incrementally add validation rules to their UIs.

WPF can create ValidationRules which developers can bind to the controls to which your property is bound. ValidationRules allow the UI developer to mix-and-match the validation code you supply. This makes sense in scenarios where some validation rules apply and others where they don't. You can build common validation logic that applies in all scenarios into your business class, then provide a set of ValidaitonRules that developers can add (or omit) depending on the scenario.

To create a validation rule, you add a class that inherits from the base ValidationRule class. After that, you just need to override the class' Validate method which will be passed the value from the control to which the ValidationRule is bound. The method must return a ValidationResult which holds a success code (True or False) and an error message:

Public Class CustomerIDCase
    Inherits ValidationRule

    Public Overrides Function Validate(ByVal value As Object,
                               ByVal cultureInfo As System.Globalization.CultureInfo) _
                               As System.Windows.Controls.ValidationResult
      Dim strValue As String = value.ToString
       
      If Text.RegularExpressions.Regex.IsMatch(strValue, "[a-z]") Then
        Return New ValidationResult(False, "CustomerID must be all uppercase")
      Else
        Return New ValidationResult(True, Nothing)
      End If
    End Function
  End Class

To apply your ValidationRule, the UI developer must first add an XML namespace that points to your ValiationRule project's namespace (in this case, CustomerValidation):

<Window …
   xmlns:l="clr-namespace:CustomerValidation"
The developer can then add your validation rule to any control's ValidationRules collection. This example, using XAML's element-based syntax for setting properties, adds the CustomerIDCase rule example to a TextBox:

<TextBox …>
    <TextBox.Text>
      <Binding Path="CustomerID" 
              Mode="TwoWay" UpdateSourceTrigger="LostFocus">
        <Binding.ValidationRules>
          <l:CustomerIDCase/>
        </Binding.ValidationRules>
      </Binding>
    </TextBox.Text>
  </TextBox>

The error messages generated by your ValidationRule will be automatically routed to the UI and displayed there -- the developer doesn't even have to set the ValidateOnDataErrors attribute.

Unfortunately, you give up a certain level of control here; you now have to count on the UI developer applying the right validation rules in the presentation layer. But you have freed the UI designer from having to worry about business logic so that the designer can concentrate on creating the application's UI. And, provided the ValidationRule is applied by the UI developer, you've ensured that it's your validation code that's being used. Who knows what the UI developers would come up with on their own?

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events