Click here to Skip to main content
15,881,092 members
Articles / Desktop Programming / WPF
Tip/Trick

Simple Validation in WPF

Rate me:
Please Sign up or sign in to vote.
4.70/5 (33 votes)
2 Dec 2013CPOL2 min read 198.3K   39   16
A very simple example of displaying validation error next to controls in WPF

Introduction

This is a simple example of validation in XAML for WPF controls and displaying error messages.

Background

I was looking for something out-of-the-box from WPF where no extra coding of style or template is needed for displaying validation errors, where we just need to code the validation logic for each control and it should automatically display an error icon or message next to the control. However, I did not find anything straightforward like that in WPF. But it can be achieved in two simple steps.

Using the Code

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 in the above text boxes, they automatically run validation and if there are validation errors, they will be displayed next to the corresponding control. In order to do this, the following two steps are needed:

  1. Create a ControlTemplate with AdornedElementPlaceHolder
  2. Implement a validation class inheriting the abstract class called ValidationRule

Here is the sample validation control template. Let us start with a very simple validation control template where all we have is a TextBlock which will display a red exclamatory sign next to the control that has an error.

XML
<ControlTemplate x:Key="validationErrorTemplate">
    <DockPanel>
        <TextBlock Foreground="Red" 
            DockPanel.Dock="Top">!</TextBlock>
        <AdornedElementPlaceholder 
           x:Name="ErrorAdorner"
        ></AdornedElementPlaceholder>
    </DockPanel>
</ControlTemplate> 

Now, let us also create a validator class by inheriting from the ValidationRule class and implementing its abstract method as below:

C#
public class NameValidator : ValidationRule
{
    public override ValidationResult Validate
      (object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (value == null)
            return new ValidationResult(false, "value cannot be empty.");
        else
        {
            if (value.ToString().Length > 3)
                return new ValidationResult
                (false, "Name cannot be more than 3 characters long.");
        }
        return ValidationResult.ValidResult;
    }
}

Let's plug this validation control template and the validation rule with control that we want to validate.

XML
<TextBox Height="23" HorizontalAlignment="Left" 
              Grid.Column="1" Grid.Row="0" Name="textBox1" 
              VerticalAlignment="Top" Width="120" 
              Validation.ErrorTemplate="{StaticResource validationErrorTemplate}"
         >
    <TextBox.Text>
        <Binding Path="Name" Mode="TwoWay" 
        UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <local:NameValidator></local:NameValidator>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox> 

When we run this now and enter a name longer than three characters long, it displays the red exclamatory sign indicating validation error.

Image 2

Now let us just replace the TextBlock in the above validation control template code (the line that is in bold) with the StackPanel containing an ellipse and a TextBlock to display the same validation error, as below:

XML
<ControlTemplate x:Key="validationErrorTemplate">
    <DockPanel>
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
        <Grid Width="12" Height="12">
            <Ellipse Width="12" Height="12" 
            Fill="Red" HorizontalAlignment="Center" 
            VerticalAlignment="Center"
                     
                     ></Ellipse>
            <TextBlock Foreground="White" FontWeight="Heavy" 
            FontSize="8" HorizontalAlignment="Center" 
            VerticalAlignment="Center" TextAlignment="Center"
                       ToolTip="{Binding ElementName=ErrorAdorner, 
                       Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                       >X</TextBlock>
        </Grid>
        <TextBlock Foreground="Red" FontWeight="12" Margin="2,0,0,0" 
                   Text="{Binding ElementName=ErrorAdorner, 
                   Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                   ></TextBlock>                    
        </StackPanel>
        <AdornedElementPlaceholder 
        x:Name="ErrorAdorner" ></AdornedElementPlaceholder>
    </DockPanel>
</ControlTemplate>

Now when we run the code and validation fails, a validation error will be displayed as shown in the screenshot below (coded validator class for age and phone number as well).

Image 3

That is all that is needed for the simplest validation error to show up next to the control. Notice in the validation control template, we are using a DockPanel as the layout control, therefore we can easily change where the error icon and error message will be displayed. We can display them on top of the control that is failing validation (as the above picture), or on the left, right, or bottom.

License

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


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMessage Closed Pin
17-Oct-21 13:04
Member 1537462717-Oct-21 13:04 
QuestionDownload Link Pin
Member 119483332-May-17 10:40
Member 119483332-May-17 10:40 
QuestionGreat Post But one Question Pin
Member 1109812519-Apr-15 20:42
Member 1109812519-Apr-15 20:42 
Questionhelp please Pin
Member 1130035511-Dec-14 2:22
Member 1130035511-Dec-14 2:22 
GeneralMy vote of 5 Pin
karthik cad/cam4-Nov-14 23:13
karthik cad/cam4-Nov-14 23:13 
QuestionDoubt In code Pin
Member 1076929223-Jul-14 22:51
Member 1076929223-Jul-14 22:51 
QuestionDoubt In code Pin
Member 1076929223-Jul-14 22:43
Member 1076929223-Jul-14 22:43 
AnswerRe: Doubt In code Pin
karthik cad/cam4-Nov-14 23:19
karthik cad/cam4-Nov-14 23:19 
Question"value cannot be empty" no fire? Pin
Allen Jolley17-Jul-14 15:21
Allen Jolley17-Jul-14 15:21 
AnswerRe: "value cannot be empty" no fire? Pin
Brian Pendleton4-Sep-14 4:58
Brian Pendleton4-Sep-14 4:58 
QuestionCode location in SkyDrive / OneDrive. Pin
Gerald Gomes1-May-14 11:18
Gerald Gomes1-May-14 11:18 
GeneralMy vote of 4 Pin
CoderMarty1-May-14 10:22
CoderMarty1-May-14 10:22 
Questioncode! please provide code! PinPopular
allen001826-Feb-14 8:32
allen001826-Feb-14 8:32 
GeneralMy vote of 4 Pin
fredatcodeproject3-Dec-13 1:26
professionalfredatcodeproject3-Dec-13 1:26 
GeneralMy vote of 5 Pin
Kevivn Robinson2-Dec-13 10:31
Kevivn Robinson2-Dec-13 10:31 
Very good work.
GeneralVery nice Pin
bestdealex1-Dec-13 23:29
bestdealex1-Dec-13 23:29 
GeneralMy vote of 5 Pin
Carsten V2.030-Nov-13 6:06
Carsten V2.030-Nov-13 6:06 

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.