Running on Empty

The few things I know, I like to share.

Using WPF ValidationRule class.

Often a developer is asked to give feedback to a user that a field is required.  In WPF applications this feedback can be accomplished using validation rules.

First, we need to create the validation rule, fortunately WPF has a base class called ValidationRule to help us.

namespace YourNameSpace
{
    public class RequiredRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null)
            {
                return new ValidationResult(false, "Value is required");
            }
            return new ValidationResult(true, null);
        }
    }
}

That wasn’t so bad, but now we need to actually use the rule on a control.

<Window
    x:Class="YourWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:customControls="clr-namespace:YourNameSpace"
    Name="YourWindowName"
>
    <Grid>
        <TextBox>
            <TextBox.Text>
                <Binding ElementName="YourWindowName" Path="YourElementName"
                         UpdateSourceTrigger="Explicit">
                    <Binding.ValidationRules>
                        <customControls:RequiredRule/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </Grid>
</Window>

  I will explain the UpdateSourceTrigger=”Explicit” in a future blog entry.

  1. Create a custom controls namespace for yourself.  I used something obvious like customControls.
  2. Use the xmlns:customControls="clr-namespace:namespacelocation" 
    header to instantiate your control class on the window.
  3. Finally, bind the control to the Binding.ValidationRules collection of your visual element.

As, always feel free to leave me a comment or suggestions for improvements.

Advertisements

December 20, 2007 - Posted by | C#, WPF

7 Comments »

  1. This validation won’t work in default mode when control is empty or blank initially.

    Customer Name field needs to check as required one.
    By default Customer name is empty, in that case this approach won’t work.
    But we already have data in field and intentionally we try to make empty inthat case this validation fires.
    I have tries all possiblity with UpdateSourceTrigger for Default, Lostfocus, Explicit,PropertyChanged

    Comment by Sachin Wandhare | September 5, 2008 | Reply

  2. More than likely your binding is incorrect. Make certain the databinding is set up correctly first. Then put a break point on the if(value==null) and debug your code. Not really a whole lot here that can go wrong.

    Comment by roecode | September 5, 2008 | Reply

    • I agree with Sachin. The validation does not work. I set the example in the same way as the article explains it.

      Comment by Anupam | September 23, 2009 | Reply

    • Having same problem. Rule does not check initially. Everything works fine after interacting at least once.

      Comment by Jo Blow | April 14, 2011 | Reply

  3. I was able to follow your example and it sure seems to work for me, although I made one change; UpdateSourceTrigger=”PropertyChange”

    One related question though – I am able to detect that the user has entered invalid data in a text box and warn them. However it doesn’t force them to correct the error. In the code behind can I detect that there is a validation error and handle it? thanks

    Comment by Dan | June 16, 2010 | Reply

  4. I tried to chnage the CultureInfo and no luck it seems it always return en-US. Any idea why?

    TIA
    Yaz

    Comment by Yazid | November 23, 2010 | Reply

  5. Loving this.

    Comment by dallas | December 2, 2010 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: