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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube