WPF validation does not pass data that cannot be saved (very good) + virtual-like database

Source: Internet
Author: User

Validation control with a single Validation rule are easy, but what if we need to validate a control using different Valida tion rules. This article tells what to achieve multiple validation on the single control under an easy and systematic the.
    • Download source-882.5 KB
Introduction

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

It would be a easy task if we had set of multiple validation like required, numeric, minimum character length, folder ex ists, 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 being validated with the below conditions:

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

Pre

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

Pre

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

Now one of the-a-is-to-Create a class and club all rules-into-one and then-use-one rule, but isn ' t it's a time consuming Job and difficult to manage at the later stage of project? Imagine How many combination of the rules we'll have the to make and if there are any logic change, we need to go back and manage Each rule with the new changes.

Background

Continue to my validation segment, previously I wrote a tip where I highlighted what to implement maximum length validation On controls, now I moved to other validation if with addition of what to implement multiple validation on the same contro L.

Using the Code

Would it is nice to having our XAML allow assigning these rules with some kind of separator and then XAML parser would handl E This list of rules on the control.

Well yes possible and I'll show you in the below steps how we can achieve this.

Single ValidationCollapse | Copy Code
<textbox x:name="Titlebox "maxlength=""Grid.column="1 "margin="0,11,0,0 "horizontalalignment= "stretch" > <binding path= " Span class= "code-string" >book.title "Validatesondataerrors="  True "Updatesourcetrigger=" propertychanged "> <Binding. validationrules> <rules:requiredrule/> </< Span class= "Code-leadattribute" >binding. validationrules> << Span class= "Code-keyword" >/binding> </textbox >             
Multiple ValidationCollapse | Copy Code
<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= "

First, we'll introduce our generic classes which would allow us to bind these multiple rules and then these rules Wo Uld is set at run time.

Collapse | Copy Code
[Markupextensionreturntype (typeofObject)]PublicAbstractClass 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 we second class would be RuleBinding class which would 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:

Collapse | Copy Code
PublicOverrideObject ProvideValue (IServiceProvider provider) {//In case multiple rules is bound then it would come like "required| NumericVarValidationrules = Validationlist.split (NewString[] {"| ",}, Stringsplitoptions.removeemptyentries);foreach (var ruleInchValidationrules) {registerrule (rule);}//Delegate binding creation etc to the base classObject val =Base. ProvideValue (provider);return Val; } ....Privatevoid Registerrule (String rulename) {ValidationRule rule;Switch (rulename) {Case"Requiredrule ": {rule =New Requiredrule (); Binding.Validationrules.add (rule);Break }Case"Rangerule ": {rule =New Minnumericrule () {MinValue = Minvaluerange, MaxValue = Maxvaluerange}; Binding.Validationrules.add (rule);Break }Case"Numericrule ": {rule =New Numericrule (); Binding.Validationrules.add (rule);break;} case  "numericnotempty": {rule = Span class= "Code-keyword" >new numericnotemptyrule (); Binding. validationrules.add (rule); break;} case  "folderexistrule": {rule = Span class= "Code-keyword" >new folderexistrule (); Binding. validationrules.add (rule); break;} case  "minlengthrule": {rule = new minlengthrule (); Binding. validationrules.add (rule); break;} } } 

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

Points of Interest

Working on WPF are fun and doing things in a simple-to-be-in-WPF is like cherry on the cake. It's always important, that we write code in a simple-to-so-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 is enough to annoy an End user. Every minute spent to create basic structure of validation are worth it and this leads a project to an exception free Succe Ssful project and saves lots of productivity.

Hope enjoyed reading this tip.

License

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

WPF validation does not pass data that cannot be saved (very good) + virtual-like database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.