DCSIMG
WPF Data Validation using .NET Data Annotations – Part I - Essential WPF

WPF Data Validation using .NET Data Annotations – Part I

Introduction

There is a beautiful declarative mechanism in the .NET framework called Data Annotations designed for use with ASP.NET Dynamic Data controls.

“The System.ComponentModel.DataAnnotations namespace provides attribute classes that are used to define metadata for ASP.NET Dynamic Data controls” [MSDN].

Thanks to the .NET Framework 4.0 Validator class we can leverage this mechanism in our own applications, no matter if using ASP.NET at all.

This time I’ll show how to use attribute based data validation on our models or view-models. Next time I’ll show how to extend my NotifyingObject class to support this mechanism.

The Problem

First, lets say that you’ve got a model or view-model and you want to validate its properties. You can override the very old IDataErrorInfo interface but what then? the code you should write is awkward and proprietary to the specific model.

Using Data Annotations in that case is a perfect solution for having generic data validation mechanism in our models or view-models.

Usage

To use the .NET Data Annotations all you have to do is to decorate your model or view-model class and/or properties with one or more of the Data Annotations attributes.

public class Person
{
    /// <remarks>
    /// Empty string or null are not allowed.
    /// Allow minimum of 2 and up to 40 uppercase and lowercase.
    /// </remarks>
    [Required
]
    [
RegularExpression(@"^[a-zA-Z''-'\s]{2,40}$"
)]       
   
public string
FirstName
    {
       
get;
set;
    }

    /// <remarks>
    /// Empty string or null are not allowed.
    /// </remarks>
    [Required
]
   
public string
LastName
    {
       
get
; set;
    }

   
/// <summary>
    /// Gets or sets the person's age.
    /// </summary>
    /// <remarks>
    /// Only values between 1-120 are allowed.
    /// </remarks>
    [Range
(1, 120)]
   
public int
Age
    {
       
get
; set;
    }
}

The model class Person above has several properties require data validation. There are several data validation attributes you can use. You can check the list here. You can also create your own. See CustomValidationAttribute class.

As with all attribute based and AOP mechanisms The only thing left is someone or something to read these attributes and do the job for you. In case of ASP.NET, it does the job for you. In our case, WPF, we should use the .NET 4 Validator class.

 

In my next post I’ll show how to use the Validator class and how extend my NotifyingObject class to use it, so stay tuned.

Published Tuesday, October 26, 2010 9:55 AM by Tomer Shamam
תגים:, , ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:
Powered by Community Server (Commercial Edition), by Telligent Systems