Introduction
In WPF, validation rules can enhance the user experience by providing real-time feedback on the validity of entered data. This means we can help prevent users from entering invalid or incorrect data, thereby reducing the chances of errors. In this article, I will demonstrate how to implement a simple email pattern-matching validation rule in WPF. You can use this example to design your own rules and apply them to various WPF controls.
Example. Email Pattern Matching Validation
Let's consider a scenario to validate user input for an email address. We'll create a custom validation rule to enforce an email pattern.
Output 1. Invalid Email Address Format
Output 2. Valid Email Address Format
Begin by creating a folder in your WPF project and adding a class named 'EmailValidation' with the following rule.
public class EmailRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is string email)
{
string emailPattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
if (Regex.IsMatch(email, emailPattern))
{
return ValidationResult.ValidResult;
}
}
return new ValidationResult(false, $"Invalid email format");
}
}
Listing 1. EmailRule.cs
Validation Rule in View
In your XAML, apply the validation rule to a TextBox's Text '<TextBox.Text>' property and adding the '<Binding.ValidationRules>' element. This will result in the highlighting of the TextBox's border in red.
<TextBox Name="EmailTextBox"
Style="{StaticResource ErrorTooltip}"
PreviewLostKeyboardFocus="EmailTextBox_PreviewLostKeyboardFocus">
<TextBox.Text>
<Binding Path="EmailID"
UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:EmailRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Listing 2. Textbox with Validation rule
Error message on Tooltip
You can also enhance the user experience by adding a tooltip to display error messages.
<Style x:Key="ErrorTooltip" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)/ErrorContent}"/>
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1"/>
</Trigger>
</Style.Triggers>
</Style>
Listing 3. Tooltip for error message
Holding Focus Until Valid Values
To prevent users from moving away until valid values are provided, you can handle the 'PreviewLostKeyboardFocus' event. You can achieve this either in the view-model with commands or directly in the code-behind.
Note. 'EmailTextBox' is the name of the TextBox from Listing 2.
private void EmailTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (EmailTextBox.DataContext is MainWindowViewModel viewModel)
{
if (Validation.GetHasError(EmailTextBox))
{
Dispatcher.BeginInvoke(new Action(() => EmailTextBox.Focus()));
}
}
}
Listing 4. PreviewLostKeyboardFocus event
Conclusion
Creating validation rules is key to maintaining data integrity. We've learned how to showcase immediate notifications about the validity of the input. Additionally, we've explored how to handle focus until valid values are provided, ensuring that only accurate data enters the application.
I have written an article on Blazor for Input Validation, which you can check out here: Implementing Validations In Blazor
I and Mahesh have written a book to master WPF, you can download it from here: WPF Simplified
Looking to dive deeper into Blazor and unlock its full potential? Check out my comprehensive guide "[Blazor Simplified]" This book offers practical insights, expert tips, and real-world examples to master Blazor. Take your skills to the next level and elevate your web development projects with the power of Blazor! That's not all! You can also explore the [Official GitHub repository] of the book, where you'll find code samples, supplementary materials, and a community of fellow Blazor enthusiasts. Let's embark on a journey to master Blazor together!