Click here to Skip to main content
11,921,316 members (62,797 online)
Click here to Skip to main content
Add your own
alternative version


88 bookmarked

Attributes-based Validation in a WPF MVVM Application

, 28 Jul 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Description of a method which uses attribute to perform user entry validation in a WPF MVVM application


In this article, I'm sharing a simple MVVM application with validation using an attribute-based approach. Basically, it means that you'll be able to describe validation rules using this syntax:

[Required(ErrorMessage = "Field 'FirstName' is required.")]
public string FirstName
        return this.firstName;
        this.firstName = value;

Here is a picture of the demo application running:

The UI requirements for the demo application are:

  • Fill various information in 3 different tabs and provide error meaningful messages and feedback to the user when a field is incorrect:

  • Give real time feedback about the completeness of the filling process using 3 approaches:
    • When a tab is fully completed, it goes from red to green:

    • The progress is shown to the user using a progress bar:

    • When everything is filled, the Save button is activated:


WPF provides several techniques in order to validate what the user enters in an application.


From the MSDN article on ValidationRules:

When you use the WPF data binding model, you can associate ValidationRules with your binding object. To create custom rules, make a subclass of this class and implement the Validate method. The binding engine checks each ValidationRule that is associated with a binding every time it transfers an input value, which is the binding target property value, to the binding source property.


From the original blog post of Marianor about using attributes with IDataErrorInfo interface:

WPF provides another validation infrastructure for binding scenarios through IDataErrorInfo interface. Basically, you have to implement the Item[columnName] property putting the validation logic for each property requiring validation. From XAML, you need to set ValidatesOnDataErrors to true and decide when you want the binding invoke the validation logic (through UpdateSourceTrigger).

Combining IDataErrorInfo and attributes

In this article, we use a technique which combines validation attributes (an explanation of each validation attribute is out of the scope of this article) and the IDataErrorInfo interface.

Overall Design

Here is the class diagram of the application’s classes:

There is nothing really new here. The MainWindow’s Content is set to the MainFormView view. The associated ViewModel, MainFormViewModel manages a set of FormViewModel which is the base ViewModel class for each tab in the View.

In order to specify to the WPF engine how to render a FormViewModelBase, all we need to do is to create a DataTemplate and gives the correct TargetType. For example, in order to associate the ProfileFormViewModel with the ProfileFormView, we create this DataTemplate:

<DataTemplate DataType="{x:Type ViewModel:ProfileFormViewModel}">
<View:ProfileFormView />

Then the DataBinding does everything to populate the content of the TabControl using this very simple XAML:

<TabControl ItemsSource="{Binding Forms}" />

This is very similar to an approach I blogged a couple of months ago (see here for more details). The new stuff resides in the ValidationViewModelBase class which is the new base class I’m introducing for ViewModel classes which need to support validation. That’s the goal of the next section of this article.

Attribute-based Validation and the IDataError Interface

The solution I’m using here to combine attributes and IDataError interface is based on the work of Marianor (full article here). I tweaked a little bit of his code in order to have a generic solution (and that’s the goal of the ValidationViewModelBase class). The basic idea is to be able to implement the IDataErrorInfo interface (and its 2 properties) in a generic way using attributes in System.ComponentModel. The class uses extensively LINQ in order to perform the validation.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

using WpfFormsWithValidationDemo.Toolkit.Behavior;

namespace WpfFormsWithValidationDemo.Toolkit.ViewModel
    /// <span class="code-SummaryComment"><summary>
</span>    /// A base class for ViewModel classes which supports validation 
    /// using IDataErrorInfo interface. Properties must defines
    /// validation rules by using validation attributes defined in 
    /// System.ComponentModel.DataAnnotations.
    /// <span class="code-SummaryComment"></summary>
</span>    public class ValidationViewModelBase : ViewModelBase, 
		IDataErrorInfo, IValidationExceptionHandler
        private readonly Dictionary<string, 
		Func<ValidationViewModelBase, object>> propertyGetters;
        private readonly Dictionary<string, ValidationAttribute[]> validators;

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets the error message for the property with the given name.
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><param name="propertyName">Name of the property</param>
</span>        public string this[string propertyName]
                if (this.propertyGetters.ContainsKey(propertyName))
                    var propertyValue = this.propertyGetters[propertyName](this);
                    var errorMessages = this.validators[propertyName]
                        .Where(v => !v.IsValid(propertyValue))
                        .Select(v => v.ErrorMessage).ToArray();

                    return string.Join(Environment.NewLine, errorMessages);

                return string.Empty;

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets an error message indicating what is wrong with this object.
        /// <span class="code-SummaryComment"></summary>
</span>        public string Error
                var errors = from validator in this.validators
                             from attribute in validator.Value
                             where !attribute.IsValid(this.propertyGetters
                             select attribute.ErrorMessage;

                return string.Join(Environment.NewLine, errors.ToArray());

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets the number of properties which have a 
        /// validation attribute and are currently valid
        /// <span class="code-SummaryComment"></summary>
</span>        public int ValidPropertiesCount
                var query = from validator in this.validators
                            where validator.Value.All(attribute => 
                            select validator;

                var count = query.Count() - this.validationExceptionCount;
                return count;

        /// <span class="code-SummaryComment"><summary>
</span>        /// Gets the number of properties which have a validation attribute
        /// <span class="code-SummaryComment"></summary>
</span>        public int TotalPropertiesWithValidationCount
                return this.validators.Count();

        public ValidationViewModelBase()
            this.validators = this.GetType()
                .Where(p => this.GetValidations(p).Length != 0)
                .ToDictionary(p => p.Name, p => this.GetValidations(p));

            this.propertyGetters = this.GetType()
                .Where(p => this.GetValidations(p).Length != 0)
                .ToDictionary(p => p.Name, p => this.GetValueGetter(p));

        private ValidationAttribute[] GetValidations(PropertyInfo property)
            return (ValidationAttribute[])property.GetCustomAttributes
			(typeof(ValidationAttribute), true);

        private Func<ValidationViewModelBase, object> 
			GetValueGetter(PropertyInfo property)
            return new Func<ValidationViewModelBase, object>
			(viewmodel => property.GetValue(viewmodel, null));

        private int validationExceptionCount;

        public void ValidationExceptionsChanged(int count)
            this.validationExceptionCount = count;

Please note I’m also exposing the number of valid properties and the total number of properties with validation (this is used in order to compute the value of the progress bar). From the developer point of view, using this class in an existing ViewModel is very straightforward: Inherit from the new ValidationViewModelBase class instead of your traditional ViewModelBase class and then add validation attributes on the properties which requires validation.

Available Attributes (from the System.ComponentModel.DataAnnotations namespace)

Name Description
RequiredAttribute Specifies that a data field value is required
RangeAttribute Specifies the numeric range constraints for the value of a data field
StringLengthAttribute Specifies the minimum and maximum length of characters that are allowed in a data field
RegularExpressionAttribute Specifies that a data field value must match the specified regular expression
CustomValidationAttribute Specifies a custom validation method to call at run time (you must implement the IsValid() method)

Dealing with Validation Exceptions

As I was working with this new approach based on attributes, I faced a problem: how to deal with validation exception. A validation exception happens when the user input is incorrect, for example if a TextBox has its Text property to an int property, then an input like "abc" (which cannot be converted of course to an int) will raise an exception.

The approach I'm proposing is based on a behavior. A complete description of what behaviors are is out of the scope of this article. For a nice description, you can check out this article.

The behavior I'm proposing must be attached to the parent UI elements which contain the input controls that can raise exception. These are a couple of lines in the XAML:

   <Behavior:ValidationExceptionBehavior />

 <!--<span class="code-comment"> rest of the code... --></span>

When this behavior is loaded, it adds an handler for the ValidationError.ErrorEvent RoutedEvent so that it is notified each time a validation error occurs. When this happens, the behavior calls a method on the ViewModel (through a simple interface in order to limit coupling) so that the ViewModel can track the number of validation errors. Here is the code of the behavior:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace WpfFormsWithValidationDemo.Toolkit.Behavior
    /// <span class="code-SummaryComment"><summary>
</span>    /// A simple behavior that can transfer the number of 
    /// validation error with exceptions
    /// to a ViewModel which supports the INotifyValidationException interface
    /// <span class="code-SummaryComment"></summary>
</span>    public class ValidationExceptionBehavior : Behavior<FrameworkElement>
        private int validationExceptionCount;

        protected override void OnAttached()
		new EventHandler<ValidationErrorEventArgs>(this.OnValidationError));

        private void OnValidationError(object sender, ValidationErrorEventArgs e)
            // we want to count only the validation error with an exception
            // other error are handled by using the attribute on the properties
            if (e.Error.Exception == null)

            if (e.Action == ValidationErrorEventAction.Added)

            if (this.AssociatedObject.DataContext is IValidationExceptionHandler)
                // transfer the information back to the viewmodel
                var viewModel = (IValidationExceptionHandler)

Progress Reporting

One of my requirements was “When a tab is fully completed, it goes from red: to green: ”. In order to realize this particular feature, I added an “IsValid” property to the FormViewModelBase class (which is the base class for all ViewModels in the TabControl). This property is updated whenever a PropertyChanged occurs by looking if the Error property (of the IDataErrorInfo interface) is empty:

protected override void PropertyChangedCompleted(string propertyName)
    // test prevent infinite loop while settings IsValid
    // (which causes an PropertyChanged to be raised)
    if (propertyName != "IsValid")
        // update the isValid status
        if (string.IsNullOrEmpty(this.Error) &&
        	this.ValidPropertiesCount == this.TotalPropertiesWithValidationCount)
            this.IsValid = true;
            this.IsValid = false;

Then a simple trigger in the XAML is enough to have the visual effect I described:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="HeaderTemplate">
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding FormName}" VerticalAlignment="Center" Margin="2" />
          <Image x:Name="image"
          <DataTrigger Binding="{Binding IsValid}" Value="False">
            <Setter TargetName="image" 
		Property="Source" Value="../Images/Warning16.png" />

In order to have the progress bar working, I’m computing the overall progress in the parent ViewModel (the one which owns the various FormViewModelBase ViewModels):

/// <span class="code-SummaryComment"><summary>
</span>/// Gets a value indicating the overall progress (from 0 to 100) 
/// of filling the various properties of the forms.
/// <span class="code-SummaryComment"></summary>
</span>public double Progress
        double progress = 0.0;
        var formWithValidation = this.Forms.Where(f => 
		f.TotalPropertiesWithValidationCount != 0);
        var propertiesWithValidation = this.Forms.Sum(f => 

        foreach (var form in formWithValidation)
            progress += (form.ValidPropertiesCount * 100.0) / propertiesWithValidation;

        return progress;

Points of Interest

The goal of this technique as I said in the introduction is to have a replacement for the traditional ValidationRules approach which complicates the XAML a lot. Using LINQ and Attributes is a nice way to implement this new possibility. While approaching the end of the writing of this article, I noticed that a similar solution is available in a famous MVVM frameworks made by Mark Smith (the MVVM Helpers).


I would like to profusely thank people who helped me to review this article: my co-worker Charlotte and Sacha Barber (CodeProject and Microsoft MVP).


  • 28th July 2010: Original version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jeremy Alles
Software Developer (Junior)
France France
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionCompare two dates Pin
SDavisworth30-Jun-15 14:43
memberSDavisworth30-Jun-15 14:43 
QuestionMessage Removed Pin
Member 115075088-Mar-15 4:18
memberMember 115075088-Mar-15 4:18 
AnswerRe: rofl Pin
SDavisworth12-Mar-15 15:28
memberSDavisworth12-Mar-15 15:28 
QuestionModification for support localizations Pin
Member 477198315-Jan-15 0:19
memberMember 477198315-Jan-15 0:19 
SuggestionEasier Error Messages Pin
claycephas13-Mar-14 8:02
memberclaycephas13-Mar-14 8:02 
QuestionCustom Validation Error Message Pin
mBonafe29-Jan-14 12:21
membermBonafe29-Jan-14 12:21 
QuestionNot Seeing ErrorMessage in the ToolTip Pin
mBonafe22-Jan-14 10:10
membermBonafe22-Jan-14 10:10 
AnswerRe: Not Seeing ErrorMessage in the ToolTip Pin
mBonafe22-Jan-14 10:24
membermBonafe22-Jan-14 10:24 
QuestionValidates on initialization Pin
Manish Kr Jha19-Aug-13 3:13
memberManish Kr Jha19-Aug-13 3:13 
AnswerRe: Validates on initialization Pin
Jeremy Alles21-Aug-13 1:01
memberJeremy Alles21-Aug-13 1:01 
QuestionUse this in Unit Tests Pin
shahgun31-Jul-13 0:38
membershahgun31-Jul-13 0:38 
AnswerRe: Use this in Unit Tests Pin
Jeremy Alles21-Aug-13 0:51
memberJeremy Alles21-Aug-13 0:51 
QuestionHi Jeremy Pin
SDavisworth20-May-13 3:59
memberSDavisworth20-May-13 3:59 
AnswerRe: Hi Jeremy Pin
Jeremy Alles21-Aug-13 0:49
memberJeremy Alles21-Aug-13 0:49 
GeneralMy vote of 5 Pin
masdket10-May-13 22:16
membermasdket10-May-13 22:16 
GeneralRe: My vote of 5 Pin
Jeremy Alles21-Aug-13 0:15
memberJeremy Alles21-Aug-13 0:15 
GeneralExcellent Post Pin
yannik steiger16-Jan-13 18:41
memberyannik steiger16-Jan-13 18:41 
GeneralRe: Excellent Post Pin
Jeremy Alles17-Jan-13 20:46
memberJeremy Alles17-Jan-13 20:46 
Generalmy vote of 5 Pin
bahman aminipour6-Nov-12 7:16
memberbahman aminipour6-Nov-12 7:16 
GeneralRe: my vote of 5 Pin
Jeremy Alles6-Nov-12 21:00
memberJeremy Alles6-Nov-12 21:00 
QuestionErrorMessage issue Pin
Goran _18-Sep-12 2:11
memberGoran _18-Sep-12 2:11 
Hi Jerremy, thanks for this great code (5 from me). One thing I do not understand. If I remove ErrorMessage from Attribute declaration, validation errors would not occur at all. Why is this happening? I am using a localization that doesn't use resource files (for some specific requirements), so I use Custom attributes for validation, where I localize messages.
So, when I remove ErrorMessage, validation stops. Do you know why?
AnswerRe: ErrorMessage issue Pin
Jeremy Alles18-Sep-12 3:16
memberJeremy Alles18-Sep-12 3:16 
GeneralRe: ErrorMessage issue Pin
Goran _18-Sep-12 12:02
memberGoran _18-Sep-12 12:02 
GeneralRe: ErrorMessage issue Pin
Goran _19-Sep-12 14:11
memberGoran _19-Sep-12 14:11 
QuestionLinked to your Article Pin
nazzyg11-Sep-12 11:49
membernazzyg11-Sep-12 11:49 
Question1) Dynamic controls? 2) Localization? Pin
Claire Streb14-Aug-12 16:35
memberClaire Streb14-Aug-12 16:35 
AnswerRe: 1) Dynamic controls? 2) Localization? Pin
Jeremy Alles25-Aug-12 0:46
memberJeremy Alles25-Aug-12 0:46 
GeneralRe: 1) Dynamic controls? 2) Localization? Pin
Claire Streb25-Aug-12 8:38
memberClaire Streb25-Aug-12 8:38 
QuestionCombobox validation Pin
Member 450897825-Jun-12 3:46
memberMember 450897825-Jun-12 3:46 
AnswerRe: Combobox validation Pin
Jeremy Alles25-Aug-12 0:42
memberJeremy Alles25-Aug-12 0:42 
GeneralMy vote of 5 Pin
Member 450897822-Jun-12 3:11
memberMember 450897822-Jun-12 3:11 
GeneralMy vote of 5 Pin
Florian.Witteler25-Apr-12 8:47
memberFlorian.Witteler25-Apr-12 8:47 
SuggestionGreat solution Pin
rliviu17-Apr-12 15:28
memberrliviu17-Apr-12 15:28 
QuestionExcellent solution! Pin
Robert Brower1-Feb-12 8:05
memberRobert Brower1-Feb-12 8:05 
GeneralCompleted with hierarchical VM and voted 5 Pin
Jac5-Oct-11 1:54
memberJac5-Oct-11 1:54 
GeneralMy vote of 5 Pin
Puchko Vasili14-Apr-11 12:26
memberPuchko Vasili14-Apr-11 12:26 
QuestionPossible Extension? Pin
Tom Thorp6-Nov-10 15:26
memberTom Thorp6-Nov-10 15:26 
Generalcross field validation Pin
Member 39408249-Sep-10 7:17
memberMember 39408249-Sep-10 7:17 
GeneralRe: cross field validation Pin
kiduk15-Jul-12 6:06
memberkiduk15-Jul-12 6:06 
GeneralSimiliar to Present Pin
thejuan10-Aug-10 22:49
memberthejuan10-Aug-10 22:49 
GeneralNice Pin
Shaun Stewart4-Aug-10 6:55
memberShaun Stewart4-Aug-10 6:55 
GeneralRe: Nice Pin
Jeremy Alles8-Aug-10 23:01
memberJeremy Alles8-Aug-10 23:01 
GeneralMy vote of 5 Pin
Shaun Stewart4-Aug-10 6:54
memberShaun Stewart4-Aug-10 6:54 
GeneralVery nice, have a 5 Pin
Sacha Barber29-Jul-10 4:59
mvpSacha Barber29-Jul-10 4:59 
GeneralRe: Very nice, have a 5 Pin
Jeremy Alles8-Aug-10 23:01
memberJeremy Alles8-Aug-10 23:01 
GeneralMy vote of 4 Pin
aman.tur29-Jul-10 0:21
memberaman.tur29-Jul-10 0:21 
GeneralRe: My vote of 4 Pin
Jeremy Alles29-Jul-10 4:36
memberJeremy Alles29-Jul-10 4:36 
GeneralYour article Pin
Member 157228-Jul-10 20:21
memberMember 157228-Jul-10 20:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151120.1 | Last Updated 28 Jul 2010
Article Copyright 2010 by Jeremy Alles
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid