Skip to main content
All docs
V23.2

Validate User Input in Blazor Grid

  • 6 minutes to read

The Grid allows you to validate input data and display errors.

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 removes focus from a data 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.

Once validation is completed, the component marks editors with colored outlines: green indicates valid values, red — invalid values. Automatically generated cell editors additionally display the following validation icons:

  • Error (for validation errors)
  • Success (indicates successful validation)

An icon’s title displays the error message. Set the column editor’s ShowValidationIcon property to false to hide validation icons.

Run Demo: Input Validation

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
// ...
    public partial class Employee {
        public int EmployeeId { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string Title { get; set; }
        public string TitleOfCourtesy { get; set; }
        public Nullable<System.DateTime> BirthDate { get; set; }
        [Required]
        [Range(typeof(DateTime), "1/1/2000", "1/1/2020",
        ErrorMessage = "HireDate must be between {1:d} and {2:d}")]
        public Nullable<System.DateTime> HireDate { get; set; }
        // ...
    }

Validation Icons

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>
    

Blazor Grid Input Validation

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 use DataAnnotationsValidator in addition to custom validators, declare it in the CustomValidators template explicitly.
EditFormTemplate or CellEditTemplate
The Grid uses the standard DataAnnotationsValidator and declared custom validators. Do not place the DataAnnotationsValidator in the edit form template to avoid validation message duplicates.

The following example uses a custom validator to evaluate the Title field value.

View Example: Custom Validation View Example: Display an error message from the Web API Service

@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;
        var dataItem = e.IsNew ? new Employee() : Northwind.Employees.Find(editModel.EmployeeId);
        if (dataItem != null) {
            dataItem.FirstName = editModel.FirstName;
            dataItem.LastName = editModel.LastName;
            dataItem.Title = editModel.Title;
            dataItem.HireDate = editModel.HireDate;
            if (e.IsNew)
                await Northwind.AddAsync(dataItem);
            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();
    }
}

Blazor Grid Editing Custom Validation

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>