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

Subscribe on YouTube