An Overview of the Implementation of ValidationRules in WPF C#

In WPF, the ValidationRule class serves the purpose of validating user input within controls such as TextBox by enabling the creation of custom validation rules. A ValidationRule can be incorporated into a binding to define specific criteria that the input must satisfy, which may include restrictions such as permitting only numeric entries or adhering to a designated range of values.

Procedures for executing the ValidationRules

Step 1. To establish a Custom ValidationRule, begin by defining a class that derives from ValidationRule. Subsequently, override the Validate method to incorporate your specific validation logic.

using System.Globalization;
using System.Windows.Controls;
namespace WpfValidationExample
{
    public class DoubleValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            // Attempt to interpret the input value as a double.
            if (double.TryParse(value as string, out double result))
            {
                return ValidationResult.ValidResult;
            }          
            // Return an error if the value does not constitute a valid double.
            return new ValidationResult(false, "The number format is invalid. Kindly input a valid decimal number.");
        }
    }
}

A detailed description of the above class

  • The DoubleValidationRule class extends the ValidationRule class, thereby creating a specialized rule for validating user input.
  • The validation method is redefined to incorporate particular validation logic. This method is invoked whenever the binding target, such as TextBox.Text, refreshes its source.
  • Upon successful parsing, the method yields ValidationResult.ValidResult, signifying that the validation has been successfully completed.

Step 2. Utilize the ValidationRule within XAML.

<Window x:Class="WpfValidationExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfValidationExample"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.Resources>
        <local:DoubleValidationRule x:Key="DoubleValidationRule" />
        <ControlTemplate x:Key="ErrorTemplate">
            <StackPanel>
                <AdornedElementPlaceholder />
                <TextBlock Foreground="Red" FontSize="12" Text="{Binding [0].ErrorContent}" />
            </StackPanel>
        </ControlTemplate>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="Double Value" Grid.Row="0" Grid.Column="0" FontSize="20" Margin="0,10,0,0" />
        
        <TextBox HorizontalAlignment="Center" Width="200" Height="40" Grid.Row="1" Grid.Column="1" Margin="20,10,0,0">
            <TextBox.Text>
                <Binding Path="DoubleValue" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" NotifyOnValidationError="True" StringFormat="F2">
                    <Binding.ValidationRules>
                        <local:DoubleValidationRule />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <!-- In the event of a validation error, display the error template. -->
                        <Trigger Property="Validation.HasError" Value="True">
                            <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
                            <Setter Property="BorderBrush" Value="Red" />
                            <Setter Property="Validation.ErrorTemplate" Value="{StaticResource ErrorTemplate}" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </Grid>
</Window>

<!-- Step 3: Validation errors can be displayed by applying a Style that emphasizes controls when validation is unsuccessful. For instance, consider incorporating an error template into the TextBox. -->
<Window.Resources>
    <local:DoubleValidationRule x:Key="DoubleValidationRule" />
    <ControlTemplate x:Key="ErrorTemplate">
        <StackPanel>
            <AdornedElementPlaceholder />
            <TextBlock Foreground="Red" FontSize="12" Text="{Binding [0].ErrorContent}" />
        </StackPanel>
    </ControlTemplate>
</Window.Resources>

The above implementation is explained as follows.

  • Create a custom ValidationRule by extending the ValidationRule class and overriding the Validate method.
  • Implement the ValidationRule in XAML by including it in the ValidationRules collection of a Binding.
  • Utilize styles or templates to visually indicate validation errors in the user interface, such as a red border or a tooltip displaying the error message.

Step 4. The results of the aforementioned implementation.

Implementation