Click here to Skip to main content
11,924,995 members (49,663 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked

WPF - Multiple Validation on Single Control

, 12 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Validation control with a single validation rule is easy, but what if we need to validate a control using different validation rules. This article tells how to achieve multiple validation on single control in an easy and systematic way.


Implementing multiple validation rules on a single control is bit difficult but not impossible. Every form has one or more controls which required to be validation on different set of logic. Since this is a very basic dependency of code that every developer has to do, this tip is dedicated only to this.

It would be an easy task if we have set of multiple validation like required, numeric, minimum character length, folder exists, numeric range rule and we just apply one or more than one rule just by putting comma or | between the rules in our XAML file. To elaborate more, the issue lets see a situation.

Assume one textbox control value needs to be validated with the below conditions:

  1. It has to be a required field.
  2. It has to be a numeric field.
  3. It should be between ranges of 1 to 100.


  1. It has to be a required Field
  2. Input value should have minimum 3 characters.


  1. It has to be a required field.
  2. Input value should be a valid directory.

Now one way is to create a class and club all rules into one and then use that one rule, but isn't it is a time consuming job and difficult to manage at the later stage of project? Imagine how many combination of rules we will have to make and if there is any logic change, we need to go back and manage each rule with the new changes.


Continue to my validation segment, previously I wrote a tip where I highlighted how to implement maximum length validation on controls, now I moved to other validation but with addition of how to implement multiple validation on the same control.

Using the Code

Would it be nice to have our XAML allow assigning these rules with some kind of separator and then XAML parser would handle this list of rules on the control.

Well yes, this is possible and I will show you in the below steps how we can achieve this.

Single Validation

<TextBox x:Name="titleBox" MaxLength="100" Grid.Column="1" Margin="0,11,0,0" HorizontalAlignment="Stretch">
                   <rules:RequiredRule />

Multiple Validation

<TextBox Text="{binding:RuleBinding Path=Book.Pages, 
        ValidationList=RequiredRule|NumericRule|RangeRule,  MinValueRange=0, MaxValueRange=999,        UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True , Mode=TwoWay}"
        Grid.Column="1" Grid.Row="6" HorizontalAlignment="Stretch"/> 

First, we will introduce our two generic classes which would allow us to bind these multiple rules and then these rules would be set at run time.

  public abstract class BindingDecoratorBase : MarkupExtension
    /// <summary>
    /// The decorated binding class.
    private Binding binding = new Binding();
  public override object ProvideValue(IServiceProvider provider)
      //create a binding and associate it with the target
      return binding.ProvideValue(provider);
protected virtual bool TryGetTargetItems(IServiceProvider provider, out DependencyObject target, out DependencyProperty dp)

Now our second class would be RuleBinding Class which will be inherited from our 1st class BindingDecoratorBase class. This class has an override of ProvideValue() method. In this method, we call the below RegisterRule() method:

public override object ProvideValue(IServiceProvider provider)
            //In case multiple rules are bound then it would come like "Required|Numeric
            var validationRules = ValidationList.Split(new string[] { "|", }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var rule in validationRules)

            //delegate binding creation etc. to the base class
            object val = base.ProvideValue(provider);
            return val;
        } .... 
private void RegisterRule(string ruleName)
            ValidationRule rule;
            switch (ruleName)
                case "RequiredRule":
                        rule = new RequiredRule();
                case "RangeRule":
                        rule = new MinNumericRule() 
            { MinValue = MinValueRange, MaxValue = MaxValueRange};
                case "NumericRule":
                        rule = new NumericRule();
                case "NumericNotEmpty":
                        rule = new NumericNotEmptyRule();
                case "FolderExistRule":
                        rule = new FolderExistRule();
                case "MinLengthRule":
                        rule = new MinLengthRule();

That's it, very simple implementation but very helpful and effective, when you would run this project you would find that tooltips are changing based on error for the same control.

Points of Interest

Working on WPF is fun and doing things in a simple way in WPF is like cherry on the cake. It is always important that we write code in a simple way so that it can be managed by other people in your absence.

Validation plays a very important role and eliminates possibilities of all those silly errors which are enough to annoy an end user. Every minute spent to create basic structure of validation is worth it and this leads a project to an exception free successful project and saves lots of productivity.

Hope you enjoyed reading this tip.


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


About the Author

Rohit Dot net
Technical Lead Mphasis Ltd
India India
Rohit Agrawal

I am working in IT industry from last 7 years and have been involved majorly in product development using C# and WinForms. I've now moved to WPF, for last 18 months or so.

My reasoning for success is:

"There is always at least one way to reach a destination! All it needs is to explore!"

Achievements : MCP, MCPD. in .net 3.5 Framework in C# with WInforms.
Worked on : C#, WinfForms, WPF, .net 3.5/4.0/4.5, Caliber, Sybase, MySql, Sql
MVVM with MEF, MVC, Scrum, XML/XSD/XSLT, TFS, DevExpress controls
VSS, Toad, Oracle, SVN, SVN Tortoise , Team Explorer.

Contact :

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Kicha Parameshwara Ekanta Raniyar14-Mar-14 0:17
memberKicha Parameshwara Ekanta Raniyar14-Mar-14 0:17 
GeneralMessage Automatically Removed Pin
13-Mar-14 22:10
memberMember 1066931613-Mar-14 22:10 
QuestionExpansion Pin
cjb11012-Mar-14 22:42
membercjb11012-Mar-14 22:42 
AnswerRe: Expansion Pin
Rohit Dot net25-Mar-14 2:04
professionalRohit Dot net25-Mar-14 2:04 

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.151125.3 | Last Updated 12 Mar 2014
Article Copyright 2014 by Rohit Dot net
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid