Really simple WPF form data validation - how to?

wpf validation mvvm
wpf validation on button click
wpf textbox validation
wpf textbox validation without binding
wpf validation error template
wpf idataerrorinfo
wpf range validation
wpf number validation

I'm having this really simple class, lets call it Customer. It look like this:

namespace TestValidation
{
     class Customer
     {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                if (String.IsNullOrEmpty(value))
                {
                    throw new Exception("Customer name is mandatory.");
                }
            }
        }
    }
}

Now, I've created a basic form, where the user can add customers to the database. The form contain simple TextBox, bounded to the Name property of Customer, and an "Add" button.

The XAML code is:

<Window x:Class="TestValidation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestValidation"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
<TextBox Margin="119,86,107,194" Name="CustomerName"
        Text="{Binding Path=Customer.Name, 
                ValidatesOnExceptions=True, 
                ValidatesOnDataErrors=True,
                UpdateSourceTrigger=PropertyChanged,
                NotifyOnValidationError=True}"
    />
        <Button Content="Add" HorizontalAlignment="Left" Margin="204,176,0,0" VerticalAlignment="Top" Width="74"/>
    </Grid>
</Window> 

From the setter of the Name property, you can understand that the name is mandatory for me, so I want an validation event to rise if the Name TextBox left blank. By validation rules of WPF - once the user focus out of the textbox, and there's no value over there - it should change the border color to red. For some reason - this is not happening, and I don't have a clue why. What is wrong in my process?

Now, I've read so many good articles about Validation in WPF (like Enforcing Complex Business Data Rules with WPF, Data validation in WPF and Validation in Windows Presentation Foundation), but none of them helped me solving my problem.

Eventually, I want the form to look like the form in Brian Noyes excellent article over the first link (Don't have 10 credits, so I can't attach a photo... sorry).

I'll be grateful if someone can explain to me how it really works.

Important note - I'm working with .Net framework 4, so I need a solution that suits this version.

I would definitely recommend using IDataErrorInfo for WPF validation since WPF already understands how to use it, and its easy to implement.

To start with, add the interface to the class containing the data you want to validate. The required methods will probably look something like this:

public class Customer : IDataErrorInfo
{
    ...

    #region IDataErrorInfo Members

    string IDataErrorInfo.Error
    {
        get { return null; }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            if (columnName == "Name")
            {
                // Validate property and return a string if there is an error
                if (string.IsNullOrEmpty(Name))
                    return "Name is Required";
            }

            // If there's no error, null gets returned
            return null;
        }
    }
    #endregion
}

Next, you need to set ValidatesOnDataErrors=True in your TextBox binding so it runs the validation whenever the Name property changes:

<TextBox Text="{Binding Path=Customer.Name, ValidatesOnDataErrors=True}" ... />

And finally, create a Validation Template in your XAML to tell WPF how to draw a validation error. Here's the style/template I usually use:

<!-- ValidatingControl Style -->
<Style TargetType="{x:Type FrameworkElement}" x:Key="ValidatingControl">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
            <Setter Property="ToolTip" Value="{Binding 
                Path=(Validation.Errors)[0].ErrorContent, 
                RelativeSource={x:Static RelativeSource.Self}}" />
        </Trigger>
    </Style.Triggers>
</Style>

Also, be sure your Customer class implements INotifyPropertyChanged so it correctly responds to UI updates. I don't see that in your code, but often people leave that out for simplicity :)

WPF Validation: How to Validate the Whole Form on the Button Click , I would definitely recommend using IDataErrorInfo for WPF validation since WPF already understands how to use it, and its easy to implement. WPF Validation: How to Validate the Whole Form on the Button Click In this tutorial, you'll learn how to add a validation field to your application that will be able to tell the user if they've

You did not specify a validation rule. The validation rule would be invoked before the control is left and then can do whatever you want to validate the inputs.

A simple example - and I guess that's what you want to do - is provided here.

Data validation in WPF, 09, 17 · Web Dev Zone · Tutorial. Like (5) User data warrants verification in just about every application containing these forms. As such, upon searching for “​WPF validation,” you'll learn how to use IDataErrorInfo. What if the In real life you will have some server communication herebut for now:. See "Data Validation" in Data Binding Overview for more information. Also, WPF provides a built-in validation rule that catches exceptions that are thrown during the update of the binding source property. For more information, see ExceptionValidationRule. See also. Data Binding Overview; How-to Topics; Related Articles

Use IDataErrorInfo for validation. this link will help you.

Simple Validation in WPF, This post is about how data validation works in WPF and the different validation In a MVVM WPF application, the view model acts as the window's DataContext: The latter can for example be very useful for bindings in Styles and Below is an example of a simple service with a single method that  WPF Validation: How to Validate the Whole Form on the Button Click. User data warrants verification in just about every application containing these forms. In all likelihood, if you have experience working with WPF application forms, you’ve had to deal with the implementation of validation in some capacity.

I think the issue might be that your class isn't implementing INotifyPropertyChanged, so isn't binding as you're expecting.

Implement the INotifyPropertyChanged interface, raise an event when the property changed and it should work.

See http://msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx for a walkthrough.

Validation in WPF, Here is a very simple form in XAML that is created which has three textbox controls: Image 1. Let us add code so that when values are entered  Under the LostFocus value, the validation process is invoked only when the end-user leaves the editor. To illustrate the binding mechanism on the EditValue property available on any of the DXEditors, consider the following simple binding: EditValue="{Binding FirstName, Mode=TwoWay}". EditValue is the target property where binding is applied.

<Binding Path=Name UpdateSourceTrigger="PropertyChanged">
  <Binding.ValidationRules>
    <ExceptionValidationRule />
  </Binding.ValidationRules>
</Binding>

http://msdn.microsoft.com/en-us/library/ms752347%28v=vs.110%29.aspx#what_is_data_binding

Please use this blog : prasadcsharp.blogspot.com

WPF Validation: How to Validate the Whole Form on the Button Click, The various options are explored and a simple WPF application is built that adds Forms require some triggering device such as a button or menu to invoke processing. Validation errors detected by the framework including data If screen real estate is at a premium, displaying error messages in a "bar"  Data validation in WPF. A common requirement for any user interface application that accepts user input is to validate the entered information to ensure that it has the expected format and type for the back-end to be able to accept and persist it.

How to: Implement Binding Validation, If you need WPF validation of the whole form it can be quite User data warrants verification in just about every application In real life you will have some server communication here…but for NET and C# development. Your view model or model will often be required to perform data validation and to signal any data validation errors to the view so that the user can act to correct them. Silverlight and WPF provide support for managing data validation errors that occur when changing individual properties that are bound to controls in the view.

Input Validation, The binding is set up to use a validation rule named AgeRangeRule so that if the user enters For the complete example, see Bind Validation sample. See "​Data Validation" in Data Binding Overview for more information. This property is really great, simple and does exactly what we need. It can cause a performance issue. Example - a grid with >=1000 rows, where validation of each row makes >=1 requests to database. After DataContext set each row will be validated and it will fire >=1000 requests to database.

Really simple WPF form data validation - how to?, This scenario and the validation rules are based on a real application I wrote for a customer in which a fairly simple form required the use of almost every validation  Fluent Validation in C# - The Powerful Yet Easy Data Validation Tool - Duration: 43:58. IAmTimCorey 33,830 views

Comments
  • I would just add for the OP that case-sensitivity is important, and if it the binding path is not the same case expectation, it will still run, but never actually bind to a property that doesn't exist :)
  • Can you explain a little more about the ValidatingControl Style? I tried it in several places in the xaml and got errors about key must bge contained in IDictionary. Is key supposed to be the actual name of my control? Do I embed it within the control tags or outside? I am new to xaml and wpf and trying to get validation to work.
  • @James The <Style> goes in your .Resources somewhere, such as <Window.Resources>, and it can be given an x:Key to reference it by. Any control that wants to use that style can reference it by key, such as <TextBlock Style="{StaticResource ValidatingControlStyleKey}" ...>
  • @Rachel Thanks for the great post here. I have tried it and it works great. Now, I would like to check that if the Customer object is Valid or not at the time of Saving it to the database. How can I check it?
  • Tried that, no help there. In the example on the link you shared, inside the TextBox tag there Validation.Error="Validation_Error" declaration which giving me the next compiling error:'TestValidation.MainWindow' does not contain a definition for 'Validation_Error' and no extension method 'Validation_Error' accepting a first argument of type 'TestValidation.MainWindow' could be found (are you missing a using directive or an assembly reference?) . What am I really missing?
  • Validation_Error is method in code behind. on validation error that method will invoke. There is a link to download full source code of that sample. Download it and try it.
  • This would be a really good answer if you gave some context on how to use the code that you specified.