Data Validation
This section explains you to validate data on errors through different approaches like through events, DataAnnotations, INotifyDataErrorInfo.
Overview
SfDataGrid provides a convenient way to validate data and indicate the errors along with its information. GridValidationMode is the dependency property that switches between the modes of validations. The validation modes are as follows:
- None: Disables the validations by Data Annotations and also by underlying Data implementations such as INotifyDataErrorInfo. By default, GridValidationMode is set to ‘None’.
- InView: Enables the validations and displays the error information in the corresponding cell. Also, you can shift the focus to other cells to view the error information.
NOTE
GridColumn.GridValidationMode takes higher priority that its behavior overrides SfDataGrid behavior.
. The following are different approaches to validate errors on data.
- Validation through INotifyDataErrorInfo
- Validation through Data Annotations
- Validation through Events
Validation through INotifyDataErrorInfo
Validation occurs with the implementation of INotifyDataErrorInfo in built-in business object and when the GridValidationMode is set to ‘InView’ mode.
The following code example illustrates how the UnitPrice field is validated . When the value is less than 50 it shows the ErrorTooltip.
public class UserInfo : INotifyDataErrorInfo
{
public IEnumerable GetErrors(string propertyName)
{
if (propertyName == "UnitPrice")
{
if (this.UnitPrice < 50)
{
List<string> errorList = new List<string>();
errorList.Add("UnitPrice Not Valid !");
return errorList;
}
}
return null;
}
}
NOTE
Event validations are not raised for GridDataTemplateColumn and GridUnboundColumn.
Validation through Data Annotations
Once the UI interactive validations are successful, the Data layer validates the corresponding values when the GridValidationMode is set to ‘InView’ mode.
NOTE
System.ComponentModel.DataAnnotations assembly is added to the reference to use DataAnnotations.
Some of the commonly used ValidationAttributes are as follows:
- StringLengthAttribute: Specifies the maximum and minimum number of characters that are allowed for an entity member.
- RequiredAttribute: Specifies that a value is provided for a property.
- RangeAttribute: Designates the minimum and maximum constraints for the associated member.
- RegularExpressionAttribute: Designates a regular expression used for validation of the associated member.
- CustomValidationAttribute: Designates a customized method to execute and to validate the entity member.
The following code example illustrates how the String Length attribute is applied to the Name field, by setting the maximum value for the length of the Name to 10.
[StringLength(10)]
public string CustomerName
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
The following screenshot displays the output.
Validation through Events
SfDataGrid offers Validation through events when a cell moves into Edit mode and its focus is lost. Validation is done through the following events:
- Cell Validation
- Row Validation
Cell Validation
In CellValidation, two events are raised when you save the changed value of a cell in the SfDataGrid. The following events are associated with CellValidation in the SfDataGrid control:
- SfDataGrid.CurrentCellValidating: Occurs when you save the changed value of a cell by shifting the focus away from the cell and by clicking another cell in the same row as the edited cell or by navigating away from the cell.
- SfDataGrid.CurrentCellValidated: Occurs after CurrentCellValidating event. This event is not raised when IsValid property of the CurrentCellValidating event is set to ‘false’.
CurrentCellValidating Event
The event handler of the CurrentCellValidating Event receives two arguments namely sender that handles SfDataGrid and CurrentCellValidatingEventArgs as objects. CurrentCellValidatingEventArgs object contains the following properties:
- IsValid: When this property is set to ‘false’, the changed value is not saved to the underlying source, and the CurrentCellValidated event is not raised.
- NewValue: Gets the new value from the edited cell in the SfDataGrid.
- OldValue: Gets the old value from the edited cell in the SfDataGrid.
- Column: Gets the Grid Column of the SfDataGrid.
- ErrorMessage: Gets or sets the error message to notify about the error. By default, this error message is displayed as an Error ToolTip.
- RowData: Gets the edited row data.
When IsValid property is set to ‘false’, the editor of the current cell does not shift to focus. When you navigate away from the cell (within the same row), the navigation is handled, and it remains focused in the current cell.
CurrentCellValidated Event
This event is raised when the current cell is validated with the new value and the IsValid property of the CurrentCellValidating event is set to ‘true’. The event handler receives two arguments namely sender that handles SfDataGrid and CurrentCellValidatedEventArgs as objects. CurrentCellValidatedEventArgs object contains the following properties:
- NewValue: Gets the new value from the edited cell in the SfDataGrid.
- OldValue: Gets the old value from the edited cell in the SfDataGrid.
- Column: Gets the Grid Column of the SfDataGrid.
- ErrorMessage: Gets the error message to notify about the error.
- RowData: Gets the edited row data.
The following code example illustrates a simple condition to handle Cell Validation. In this example, the UnitPrice field does not exceed 50t, but when it does, an error message is displayed and the focus is not allowed to move anywhere.
private void sfGrid_CurrentCellValidating(object sender, Syncfusion.UI.Xaml.Grid.CurrentCellValidatingEventArgs args)
{
if (args.Column.MappingName == "UnitPrice" && Convert.ToInt32(args.NewValue) > 50)
{
args.ErrorMessage = "UnitPrice Must be below 50";
args.IsValid = false;
}
}
The following screenshot displays the output.
Row Validation
In SfDataGridRowValidation, two events are raised when you edit a cell in a row, and then you can move the focus from the edited row. The following events are associated with Row Validation in the SfDataGrid control:
-
SfDataGrid.RowValidating: Occurs when you save the changed value of a cell by shifting the focus away from the cell and by clicking another cell in a different row or by navigating away from the cell (navigation within the row is allowed).
-
SfDataGrid.RowValidated: Occurs after the RowValidating event. This event is not raised when IsValid property of the RowValidating event is set to ‘false’.
RowValidating Event
The event handler receives two arguments namely sender that handles SfDataGrid and RowValidatingEventArgs as objects. RowValidatingEventArgs object contains the following properties:
- IsValid: When this property is set to ‘false’, the changed value is not saved to the underlying source, and the RowValidated event is not raised.
- ErrorMessages: It is a dictionary of strings that holds the Column Name as its key and the error message as its value. This error message notifies you about the error. By default, this error message is displayed as an ErrorToolTip.
- RowData: Gets the edited row data
- RowIndex: Gets the row index.
When the IsValid property is set to ‘false’, the editor of the current cell does not shift to focus. When you navigate away from the cell (outside the current row) that is in edit mode, the navigation is handled within the current row alone.
RowValidated Event
This event is raised when the row is validated with the updated source, and the Row Validating event’s IsValid is set to ‘true’. The event handler receives two arguments namely sender that handles SfDataGrid and RowValidatedEventArgs as objects.
RowValidatedEventArgs object contains the following properties.
- ErrorMessages: Gets the error message to notify you about the error.
- RowData: Gets the edited row data
- RowIndex: Gets the row index.
The following code example illustrates a simple condition to handle Row Validation. In this example, the sum of Expense and Freight is a minimum of 3000, where this is eligible for the discounted price.
private void sfGrid_RowValidating(object sender, Syncfusion.UI.Xaml.Grid.RowValidatingEventArgs args)
{
var record = args.RowData as OrderInfo;
if (record.Quantity < 20)
{
args.ErrorMessages.Add("Quantity", "Quantity should be above 20");
args.IsValid = false;
}
}