Validate Data Input

  • 5 min to read

The DataGridView allows you to validate new values in in-place cell editors or edit form, indicate errors, and prevent saving invalid data to the data source.

In-Place Editors

This example shows how to validate a new cell value when a user modified it in an in-place cell editor and moves focus to another cell.

The DataGridView instance is bound to a collection of orders, and its Quantity column allows users to enter positive numbers only. If a new cell value does not pass validation, an error message is displayed and the user cannot move focus to another cell until the error is corrected.

Cell Validation

Follow the steps below to validate cell values:

  1. Specify Validation Rules
    Subscribe to the DataGridView.ValidateCell event, and implement validation logic in the event handler.
    Use the event parameter's OldValue and NewValue properties to get the cell's original and new value (the value that should be validated). The FieldName and RowHandle properties allow you to obtain the column and row that contain the cell whose value is being edited.
    If a cell value fails validation, set the ErrorContent property to the string that describes the validation error. A user cannot move focus to another cell until the error is fixed and the ErrorContent string is empty.
  2. Indicate Errors
    Handle the DataGridView.ValidationError event to provide a response to entering invalid data (for example, show validation error message to users). This event parameter's ValidationErrorEventArgs.ErrorContent property contains the error description assigned to the DataGridValidationEventArgs.ErrorContent property in the ValidateCell event hander.
<dxg:DataGridView x:Name="grid" ItemsSource="{Binding Orders}" 
                  ValidateCell="Grid_ValidateCell"
                  ValidationError="Grid_ValidationError">
    <!-- ... -->
</dxg:DataGridView>
using DevExpress.XamarinForms.DataGrid;
// ...

private void Grid_ValidateCell(DataGridValidationEventArgs e) {
    if (e.FieldName == "Quantity" && e.NewValue is int) { 
        if ((int)e.NewValue <= 0) {
            e.ErrorContent = "The value must be positive.";
            return;
        }
    }
    if (e.FieldName == "Quantity" && e.NewValue is String) {
        if (string.IsNullOrEmpty((string)e.NewValue)) {
            e.ErrorContent = "The value is required.";
            return;
        }
        int result;
        if (!int.TryParse((string)e.NewValue, out result)) {
            e.ErrorContent = "Only numeric values are accepted.";
            return;
        }
    }
}

private void Grid_ValidationError(ValidationErrorEventArgs e) {
    DisplayAlert("Input Error", e.ErrorContent, "OK");
}

Edit Form

This example shows how to validate cell values that users enter in the edit form.

Edit Form Validation

You can verify each value after a user modifies it (in the default edit form only) or validate the entire form (default or custom) when a user closes it.

Validate a Value Once It Is Entered

Use the EditFormPage.ValidateCell event that occurs after a user changes a cell value in the default edit form and moves focus from the editor.

In the event hander:

  1. Specify Validation Rules
    Use the event parameter's OldValue and NewValue properties to get the cell's original and new value (the value that should be validated). The FieldName and RowHandle properties allow you to obtain the column and row that contain the cell whose value is being edited.
  2. Indicate an Error
    If the entered value fails validation, set the ErrorContent property to the validation error description.
    The edit form displays this text below the corresponding invalid value once a user moves focus from the current editor. The error is indicated and the edit form cannot be closed until the value is valid.
    The default view of the edit form provides a set of properties to customize the font and position of error messages: ErrorFontColor, ErrorFontSize, ErrorFontAttributes, ErrorFontFamily, ErrorTopOffset, and ErrorMinBottomOffset.
<dxg:DataGridView x:Name="grid" ItemsSource="{Binding Orders}" 
                  Tap="Grid_Tap">
    <!-- ... -->
</dxg:DataGridView>
using DevExpress.XamarinForms.DataGrid;
// ...

private void Grid_Tap(object sender, DataGridGestureEventArgs e) {
    if (e.Item != null) {
        var editForm = new EditFormPage(grid, grid.GetRow(e.RowHandle).Item);
        editForm.ValidateCell += EditForm_ValidateCell;    
        Navigation.PushAsync(editForm);
    }
}

private void EditForm_ValidateCell(DataGridValidationEventArgs e) {
    if (e.FieldName == "Quantity" && e.NewValue is int) {
        if ((int)e.NewValue <= 0) {
            e.ErrorContent = "The value must be positive.";
        }
    }
    else if (e.FieldName == "Date" && (DateTime)e.NewValue > DateTime.Now.Date)
        e.ErrorContent = "The date value cannot be in the future.";
}

Validate Values When Closing the Edit Form

Use the EditFormPage.ValidateForm event that occurs after a user changes the values and tries to close the edit form.

In the event hander:

  1. Specify Validation Rules
    Use the event parameter's Values property to access all values that the form's editors currently contain. Field names of the grid's columns (FieldName) are keys in this dictionary.
  2. Indicate errors
    If the entered value fails validation, add an error to the Errors dictionary with the corresponding column field as the key and the error description as the value.
    The default edit form automatically displays these errors below invalid values once a user tries to close the edit form. Each error is displayed until the corresponding value is corrected and the edit form cannot be closed until all values pass validation.
    If you create a custom view for the grid's edit form, you can bind your template's elements to the Errors collection to display validation errors.
<dxg:DataGridView x:Name="grid" ItemsSource="{Binding Orders}" 
                  Tap="Grid_Tap">
    <!-- ... -->
</dxg:DataGridView>
using DevExpress.XamarinForms.DataGrid;
// ...

private void Grid_Tap(object sender, DataGridGestureEventArgs e) {
    if (e.Item != null) {
        var editForm = new EditFormPage(grid, grid.GetRow(e.RowHandle).Item);
        editForm.ValidateForm += EditForm_ValidateForm;
        Navigation.PushAsync(editForm);
    }
}

private void EditForm_ValidateForm(EditFormValidationEventArgs e) {
    if ((int)e.Values["Quantity"] <= 0) {
        e.Errors.Add("Quantity", "The value must be positive.");
    }
    if ((DateTime)e.Values["Date"] > DateTime.Now.Date)
        e.Errors.Add("Date", "The date value cannot be in the future.");
}