Validate User Input in Blazor Grid
- 7 minutes to read
The Grid allows you to validate user input and display validation results.
Important
You should not rely on grid input validation alone to secure your Blazor-powered app. Grid validation is designed to improve usability. A threat actor can bypass validation and send malicious data to the server. To minimize security related threats/risks, you must validate user input using multiple strategies. Refer to the following topic for more information: Validate User Input.
Built-In Validation
The Grid component uses the DataAnnotationsValidator to validate user input based on data annotation attributes defined in an edit model and display error messages. The Grid validates editor values in the following cases:
- A user modifies a data editor’s value and removes focus from this editor.
- A user attempts to save changes.
- The SaveChangesAsync() method is called.
In EditCell
mode, the Grid component also validates cell values when focus leaves the edited row. The component prevents users from editing another row until they address all validation errors.
Based on the edit mode, the Grid component displays validation results in one of the following ways.
Validation in Cell Editors
In EditRow
and EditCell
edit modes, the Grid component displays error validation icons in cell editors. Users can hover the mouse pointer over an icon to display the corresponding error message in the tooltip.
Enable an editor’s ShowValidationSuccessState
property to display a success icon when validation passes. The GlobalOptions.ShowValidationSuccessState setting allows you to enable success validation icons for all editors inside and outside the Grid component.
The GlobalOptions.ShowValidationIcon property does not affect editors displayed in Grid cells. To hide validation icons in a cell editor, set its ShowValidationIcon
property to false
.
Validation in Edit Forms
In EditForm
and PopupEditForm
edit modes, the Grid component uses the standard form validation technique. If validation fails, the Grid component marks editors with red outlines and displays error validation icons. Users can hover the mouse pointer over an icon to display the corresponding error message in the tooltip.
Enable the editor’s ShowValidationSuccessState
property to display green outline and validation icon after successful validation:
<DxGrid Data="DataSource"
KeyFieldName="EmployeeId"
EditModelSaving="Grid_EditModelSaving"
DataItemDeleting="Grid_DataItemDeleting"
CustomizeDataRowEditor="Grid_CustomizeDataRowEditor">
<Columns>
<DxGridCommandColumn Width="160px" />
<DxGridDataColumn FieldName="FirstName" />
<DxGridDataColumn FieldName="LastName" />
<DxGridDataColumn FieldName="Title" />
<DxGridDataColumn FieldName="HireDate" />
</Columns>
<EditFormTemplate Context="EditFormContext">
@{
var employee = (EditableEmployee)EditFormContext.EditModel;
}
<DxFormLayout CssClass="w-100">
<DxFormLayoutItem Caption="First Name:" ColSpanMd="6">
@EditFormContext.GetEditor("FirstName")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Last Name:" ColSpanMd="6">
@EditFormContext.GetEditor("LastName")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Title:" ColSpanMd="6">
@EditFormContext.GetEditor("Title")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Hire Date:" ColSpanMd="6">
@EditFormContext.GetEditor("HireDate")
</DxFormLayoutItem>
</DxFormLayout>
</EditFormTemplate>
</DxGrid>
@code {
IEnumerable<EditableEmployee> DataSource { get; set; }
void Grid_CustomizeDataRowEditor(GridCustomizeDataRowEditorEventArgs e) {
var settings = (IEditSettings)e.EditSettings;
settings.ShowValidationSuccessState = true;
}
// ...
}
Disable an editor’s ShowValidationIcon
property to hide validation icons in this editor. Specify GlobalOptions.ShowValidationIcon and GlobalOptions.ShowValidationSuccessState properties to customize validation results for editors in the Grid edit form and standard EditForm.
Display Validation Message
When you define EditFormTemplate or CellEditTemplate, you can use any of the following techniques to display validation messages:
- Use Blazor’s standard ValidationMessage component to display messages for individual data editors.
- Use the template context’s
EditContext
property to access validation messages and display them manually. Use the ValidationSummary component to summarize validation messages.
<DxGrid ...> <Columns> @* ... *@ </Columns> <EditFormTemplate Context="editFormContext"> <DxFormLayout> <DxFormLayoutItem Caption="First Name:" ColSpanMd="6"> @EditFormContext.GetEditor("FirstName") </DxFormLayoutItem> <DxFormLayoutItem Caption="Last Name:" ColSpanMd="6"> @EditFormContext.GetEditor("LastName") </DxFormLayoutItem> <DxFormLayoutItem Caption="Title:" ColSpanMd="6"> @EditFormContext.GetEditor("Title") </DxFormLayoutItem> <DxFormLayoutItem Caption="Hire Date:" ColSpanMd="6"> @EditFormContext.GetEditor("HireDate") </DxFormLayoutItem> <DxFormLayoutItem ColSpanMd="12"> <ValidationSummary /> </DxFormLayoutItem> </DxFormLayout> </EditFormTemplate> </DxGrid>
Custom Validation
You can create custom validator components as described in the following Microsoft topic: Validator components.
To enable custom validation in the Grid, declare validator components in one of the following templates:
- CustomValidators
- Declared validators override the standard
DataAnnotationsValidator
. If you need to useDataAnnotationsValidator
in addition to custom validators, declare it in theCustomValidators
template explicitly. - EditFormTemplate or CellEditTemplate
- The Grid uses the standard
DataAnnotationsValidator
and declared custom validators. Do not place theDataAnnotationsValidator
in the edit form template to avoid validation message duplicates.
The following example uses a custom validator to evaluate the Title field value.
@page "/"
@using CustomValidation.Models
@using Microsoft.EntityFrameworkCore
@inject IDbContextFactory<NorthwindContext> NorthwindContextFactory
@implements IDisposable
<DxGrid Data="GridDataSource"
EditModelSaving="OnEditModelSaving"
CustomizeDataRowEditor="OnCustomizeDataRowEditor"
CustomizeEditModel="OnCustomizeEditModel"
KeyFieldName="EmployeeId">
<Columns>
<DxGridCommandColumn DeleteButtonVisible="false" />
<DxGridDataColumn FieldName="FirstName" />
<DxGridDataColumn FieldName="LastName" />
<DxGridDataColumn FieldName="Title" />
<DxGridDataColumn FieldName="HireDate" />
</Columns>
<EditFormTemplate Context="editFormContext">
<DxFormLayout>
<DxFormLayoutItem Caption="First Name:">
@editFormContext.GetEditor("FirstName")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Last Name:">
@editFormContext.GetEditor("LastName")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Title:">
@editFormContext.GetEditor("Title")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Hire Date:">
@editFormContext.GetEditor("HireDate")
</DxFormLayoutItem>
</DxFormLayout>
</EditFormTemplate>
<CustomValidators>
<MyCustomValidator DataItemValidating="ValidateGridData" />
</CustomValidators>
</DxGrid>
@code {
IEnumerable<object> GridDataSource { get; set; }
NorthwindContext Northwind { get; set; }
void ValidateGridData(ValidationMessageStoreEventArgs e) {
var employee = (Employee)e.EditModel;
if (employee.Title == null || !employee.Title.Contains("Sales")) {
e.AddError(nameof(employee.Title), "The Title field value should contain 'Sales'.");
}
}
protected override async Task OnInitializedAsync() {
Northwind = NorthwindContextFactory.CreateDbContext();
GridDataSource = await Northwind.Employees.ToListAsync();
}
void OnCustomizeEditModel(GridCustomizeEditModelEventArgs e) {
if(e.IsNew) {
var editModel = (Employee)e.EditModel;
editModel.EmployeeId = GridDataSource.Count() + 1;
}
}
async Task OnEditModelSaving(GridEditModelSavingEventArgs e) {
var editModel = (Employee)e.EditModel;
if (e.IsNew)
await Northwind.AddAsync(editModel);
else
e.CopyChangesToDataItem();
await Northwind.SaveChangesAsync();
GridDataSource = await Northwind.Employees.ToListAsync();
}
void OnCustomizeDataRowEditor(GridCustomizeDataRowEditorEventArgs e) {
if(e.EditSettings is ITextEditSettings settings)
settings.ShowValidationIcon = true;
}
public void Dispose() {
Northwind?.Dispose();
}
}
Disable Validation
Set the ValidationEnabled option to false
to disable input validation in DevExpress data editors located in the edit form or edit cells.
<DxGrid Data="Data"
...
ValidationEnabled="false">
@* ... *@
</DxGrid>
To disable validation in an editor, set its ValidationEnabled property to false
.