Back to Devexpress

Input Validation

wpf-7076-controls-and-libraries-data-editors-common-features-input-validation.md

latest16.9 KB
Original Source

Input Validation

  • Apr 18, 2025
  • 8 minutes to read

Input Validation allows you to reduce data entry errors and notify users of invalid input.

Automatic Validation Using Masks

DevExpress Data Editors validate user input when input masks are enabled. Masks let you specify the pattern for input values and users cannot enter text that is not permitted. In masked mode, entered values always match edit masks.

For more information, see Masked Input.

Event-Based Validation

If an editor’s BaseEdit.CausesValidation property is set to true, the BaseEdit.Validate event is raised for the editor.

Handle the BaseEdit.Validate event to validate a newly entered value. In the event handler, you can implement custom validation algorithms. This validation type is useful for standalone editors.

The following example shows how to handle the BaseEdit.Validate event to implement a custom validation procedure.

The image below shows the result:

xaml
<dxe:TextEdit x:Name="dxTextEdit"
          ValidateOnTextInput="False"
          Validate="dxTextEdit_Validate"/>
csharp
private void dxTextEdit_Validate(object sender, DevExpress.Xpf.Editors.ValidationEventArgs e) {
    // e.Value - the processed input value
    if (e.Value == null) return;
    if (e.Value.ToString().Length > 4) return;
    // Set the e.IsValid property to 'false' if the input value is invalid
    e.IsValid = false;
    // Specifies the error icon type
    e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Information;
    // Specifies the error text
    e.ErrorContent = "User ID is less than five symbols. Please correct.";
}
vb
Private Sub dxTextEdit_Validate(ByVal sender As Object, ByVal e As DevExpress.Xpf.Editors.ValidationEventArgs)
    ' e.Value - the processed input value
    If e.Value Is Nothing Then Return
    If e.Value.ToString().Length > 4 Then Return
    ' Set the e.IsValid property to 'false' if the input value is invalid
    e.IsValid = False
    ' Specifies the error icon type
    e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Information
    ' Specifies the error text
    e.ErrorContent = "User ID is less than five symbols. Please correct."
End Sub

Validate Event Triggers

Use the ValidationEventArgs.UpdateSource property to obtain information on why the BaseEdit.Validate event was raised.

Editor validation can be fired in the following cases:

You can call the BaseEdit.DoValidate method to validate user input at any moment.

Display Errors

Indicate Invalid Input Value

To indicate an invalid input, set the event argument’s ValidationEventArgs.IsValid property to false.

Error Icon

The error icon is displayed in the editor that fails validation. To hide the error icon, set the ShowError property to False.

Use the ValidationEventArgs.ErrorType property to specify the type of icon that indicates an error.

Error Message

An error message is displayed within the tooltip when the mouse pointer hovers over an error icon. To hide a tooltip with an error message, set the ShowErrorToolTip property to False.

Use the ValidationEventArgs.ErrorContent property to specify text for an error message.

Display an Error with a SetError Method

You can use the following methods to mark an input value as invalid and specify the error’s text and icon:

The following code sample illustrates how to customize the error with a SetError(Object, ErrorType) method call:

xaml
<dxe:TextEdit x:Name="dxTextEdit"
          ValidateOnTextInput="False"
          Validate="dxTextEdit_Validate"/>
csharp
private void dxTextEdit_Validate(object sender, DevExpress.Xpf.Editors.ValidationEventArgs e) {
    // e.Value - the processed input value
    if (e.Value == null || e.Value.ToString().Length > 4) return;
    // Specifies the error text and icon.
    // If the error text is not 'null', the processed value is marked as invalid.
    e.SetError(
        "User ID is less than five symbols. Please correct.",
        DevExpress.XtraEditors.DXErrorProvider.ErrorType.Information);
}
vb
Private Sub dxTextEdit_Validate(ByVal sender As Object, ByVal e As DevExpress.Xpf.Editors.ValidationEventArgs)
    ' e.Value - the processed input value
    If e.Value Is Nothing OrElse e.Value.ToString().Length > 4 Then Return
    ' Specifies the error text and icon.
    ' If the error text is not 'null', the processed value is marked as invalid.
    e.SetError(
        "User ID is less than five symbols. Please correct.",
        DevExpress.XtraEditors.DXErrorProvider.ErrorType.Information)
End Sub

Validate Using IDataErrorInfo

The IDataErrorInfo interface is the standard mechanism for data validation in WPF. You can use this interface to implement validation rules for each property or the entire object.

The code sample below demonstrates how to implement the IDataErrorInfo interface and enable validation in data editors.

xaml
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:InputValidationExample"
        xmlns:dxlc="http://schemas.devexpress.com/winfx/2008/xaml/layoutcontrol" 
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" 
        x:Class="InputValidationExample.MainWindow"
        Title="MainWindow" Height="450" Width="650">
    <Grid>

        <dxlc:DataLayoutControl 
                            CurrentItem="{Binding}"
                            AutoGenerateItems="False"
                            HorizontalAlignment="Left"
                            Width="250">
            <dxlc:DataLayoutItem Label="User ID">
                <dxe:TextEdit EditValue="{Binding UserID, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
            </dxlc:DataLayoutItem>
            <dxlc:DataLayoutItem Label="Name">
                <dxe:TextEdit EditValue="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
            </dxlc:DataLayoutItem>
        </dxlc:DataLayoutControl>
    </Grid>
</Window>
csharp
using System.ComponentModel;
using System.Windows;

namespace InputValidationExample {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            DataContext = new Employee() { Name = "Thomas A. Anderson", UserID = "NEO" };
        }
    }

    public class Employee: IDataErrorInfo {
        public string UserID { get; set; }
        public string Name { get; set; }

        public string Error {
            get {
                return this["UserID"] != null || this["Name"] != null ? "Correct the input values." : null;
            }
        }

        public string this[string columnName] {
            get {
                switch (columnName) {
                    case "UserID":
                        return string.IsNullOrEmpty(UserID) || UserID?.Length < 4 ? "User ID must have 4 symbols." : null;
                    case "Name":
                        return string.IsNullOrEmpty(Name)? "Name is required": null;
                    default:
                        return null;
                }
            }
        }
    }
}
vb
Imports System.ComponentModel

Namespace InputValidationExample
    Public Partial Class MainWindow
        Inherits Window

        Public Sub New()
            InitializeComponent()
            DataContext = New Employee() With {
                .Name = "Thomas A. Anderson",
                .UserID = "NEO"
            }
        End Sub
    End Class

    Public Class Employee
        Implements IDataErrorInfo

        Public Property UserID As String
        Public Property Name As String

        Public ReadOnly Property [Error] As String Implements IDataErrorInfo.Error
            Get
                Return If(Not Equals(Me("UserID"), Nothing) OrElse Not Equals(Me("Name"), Nothing), "Correct the input values.", Nothing)
            End Get
        End Property

        Default Public ReadOnly Property Item(ByVal columnName As String) As String Implements IDataErrorInfo.Item
            Get

                Select Case columnName
                    Case "UserID"
                        Return If(String.IsNullOrEmpty(UserID) OrElse UserID?.Length < 4, "User ID must have 4 symbols.", Nothing)
                    Case "Name"
                        Return If(String.IsNullOrEmpty(Name), "Name is required", Nothing)
                    Case Else
                        Return Nothing
                End Select
            End Get
        End Property
    End Class
End Namespace

The image below illustrates the result.

Validate Using DataAnnotation Attributes

You can use Data Annotation attributes to validate in-place editors in the following controls:

Standalone data editors do not support Data Annotation attributes because they have no access to the bound property’s metadata.

You can do the following as a workaround:

  1. Implement the IDataErrorInfo interface based on your data object.
  2. Use the DevExpress.Mvvm.IDataErrorInfoHelper when you implement the IDataErrorInfo.Item[String] property. The helper’s IDataErrorInfoHelper.GetErrorText(Object, String) method returns error text for each data item’s field.

The following code sample demonstrates how to use IDataErrorInfoHelper to implement the IDataErrorInfo interface based on the specified Data Annotation attributes :

xaml
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:InputValidationExample"
        xmlns:dxlc="http://schemas.devexpress.com/winfx/2008/xaml/layoutcontrol" 
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" 
        x:Class="InputValidationExample.MainWindow"
        Title="MainWindow" Height="450" Width="650">
    <Grid>

        <dxlc:DataLayoutControl 
                            CurrentItem="{Binding}"
                            AutoGenerateItems="False"
                            HorizontalAlignment="Left"
                            Width="250">
            <dxlc:DataLayoutItem Label="User ID">
                <dxe:TextEdit EditValue="{Binding UserID, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
            </dxlc:DataLayoutItem>
            <dxlc:DataLayoutItem Label="Name">
                <dxe:TextEdit EditValue="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
            </dxlc:DataLayoutItem>
        </dxlc:DataLayoutControl>
    </Grid>
</Window>
csharp
using DevExpress.Mvvm;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows;

namespace InputValidationExample {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            DataContext = new Employee() { Name = "Thomas A. Anderson", UserID = "NEO" };
        }
    }

    public class Employee: IDataErrorInfo {
        [Required, MinLength(4, ErrorMessage = "User ID is less than five symbols. Please correct.")]
        public string UserID { get; set; }
        [Required]
        public string Name { get; set; }

        public string Error {
            get {
                return string.Empty;
            }
        }

        public string this[string columnName] {
            get {
                return IDataErrorInfoHelper.GetErrorText(this, columnName);
            }
        }
    }
}
vb
Imports DevExpress.Mvvm
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations

Namespace InputValidationExample
    Public Partial Class MainWindow
        Inherits Window

        Public Sub New()
            InitializeComponent()
            DataContext = New Employee() With {
                .Name = "Thomas A. Anderson",
                .UserID = "NEO"
            }
        End Sub
    End Class

    Public Class Employee
        Implements IDataErrorInfo

        <Required, MinLength(4, ErrorMessage:="User ID is less than five symbols. Please correct.")>
        Public Property UserID As String
        <Required>
        Public Property Name As String

        Public ReadOnly Property [Error] As String Implements IDataErrorInfo.Error
            Get
                Return String.Empty
            End Get
        End Property

        Default Public ReadOnly Property Item(ByVal columnName As String) As String Implements IDataErrorInfo.Item
            Get
                Return IDataErrorInfoHelper.GetErrorText(Me, columnName)
            End Get
        End Property
    End Class
End Namespace

Tip

The POCO View Models can automatically implement the IDataErrorInfo interface based on the specified Data Annotation attributes. Refer to the Automatic IDataErrorInfo Implementation section for more information.

Validation Features

DevExpress data editors support the following validation features:

  • Trigger validation

  • Block focus transition

  • Reset invalid values

  • Appearance customization

See Also

Input Validation

Lesson 4 - Implement Input Validation using ValidationRules