Input Validation
- 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 which is not permitted. In masked mode, entered values always match the 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 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:
<dxe:TextEdit x:Name="dxTextEdit"
ValidateOnTextInput="False"
Validate="dxTextEdit_Validate"/>
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.";
}
Validate Event Triggers
Use the ValidationEventArgs.UpdateSource property for information on why the BaseEdit.Validate event was raised.
Editor validation can be fired in the following cases:
- The editor is about to lose focus.
- An end user enters a symbol in the editor’s edit box (if the BaseEdit.ValidateOnTextInput option is
true
). - An end user has pressed Enter (if the BaseEdit.ValidateOnEnterKeyPressed option is
true
).
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 Text
Use the ValidationEventArgs.ErrorContent property to specify the validation error’s text/content. This text is displayed within an error tooltip:
Error Icon
Use the ValidationEventArgs.ErrorType property to specify the type of icon that indicates an error.
Display an Error With a SetError Method
You can use the following methods to mark an input value as invalid, specify error text, and error icon:
The code sample below illustrates how to customize the error with a SetError(Object, ErrorType) method call.
<dxe:TextEdit x:Name="dxTextEdit"
ValidateOnTextInput="False"
Validate="dxTextEdit_Validate"/>
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);
}
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.
<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>
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;
}
}
}
}
}
The image below illustrates the result.
Validate Using DataAnnotation Attributes
You can use the Data Annotation Attributes to validate in-place editors in the following controls:
- GridControl,
- TreeListControl,
- DataLayoutControl (for automatically generated editors),
- PropertyGridControl.
Standalone data editors do not support the Data Annotation Attributes because they have no access to the bound property’s metadata.
You can do the following as a workaround:
- Implement the IDataErrorInfo interface based on your data object.
- 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 code sample below demonstrates how to use IDataErrorInfoHelper to implement the IDataErrorInfo interface based on the specified Data Annotation Attributes attributes:
<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>
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);
}
}
}
}
Tip
The POCO View Models can automatically implement the IDataErrorInfo interface based on the specified Data Annotation Attributes attributes. Refer to the Automatic IDataErrorInfo Implementation section for more information.
Validation Features
DevExpress data editors support the following validation features:
Trigger validation
You can specify when data validation should take place: with each text modification operation, when users press Enter, or when users try to move focus away from the editor (see BaseEdit.ValidateOnTextInput, BaseEdit.ValidateOnEnterKeyPressed).
Block focus transition
An editor can block focus transition to other controls until a valid value is entered (see BaseEdit.InvalidValueBehavior).
Reset invalid values
You can call the BaseEdit.ClearError method to reset invalid values. End users can press Esc to reset invalid values.
Appearance customization
You can use the BaseEdit.ValidationErrorTemplate property to change the template of the validation error’s content, and the BaseEdit.ErrorToolTipContentTemplate property to customize the template of the error’s tooltip content.