Validate Grid Data
- 5 minutes to read
This topic describes how to validate data in ASPxGridView data rows and display error icons/messages for invalid fields.
Validate Rows
Handle the ASPxGridView.RowValidating event to validate grid rows on the server side. ASPxGridView raises this event when you call the ASPxGridView.DoRowValidation method or a user clicks the “Save changes” button.
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="ObjectDataSource1" KeyFieldName="Id" OnRowValidating="grid_RowValidating" ...>
<Columns>
<dx:GridViewCommandColumn ShowNewButtonInHeader="true" ShowEditButton="true" />
<dx:GridViewDataTextColumn Caption="First Name" FieldName="FirstName" />
<dx:GridViewDataTextColumn Caption="Last Name" FieldName="LastName" />
<dx:GridViewDataTextColumn Caption="Age" FieldName="Age" VisibleIndex="3" PropertiesTextEdit-MaskSettings-Mask="99" />
<dx:GridViewDataTextColumn Caption="E-mail" FieldName="Email" Settings-AllowEllipsisInText="true" />
<dx:GridViewDataDateColumn Caption="Arrival Date" FieldName="ArrivalDate" />
</Columns>
</dx:ASPxGridView>
protected void grid_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e) {
foreach (GridViewColumn row in grid.Columns) {
GridViewDataColumn dataRow = row as GridViewDataColumn;
if (dataRow == null) continue;
if (e.NewValues[dataRow.FieldName] == null)
e.Errors[dataRow] = "Value cannot be null.";
}
if (e.NewValues["FirstName"] != null &&
e.NewValues["FirstName"].ToString().Length < 6) {
e.Errors[(GridViewDataColumn)grid.Columns["FirstName"]] = "Field value must be at least six characters long.";
}
if (e.Errors.Count > 0) e.RowError = "Please fill in all fields.";
}
Use the ASPxGridBehaviorSettings.EncodeErrorHtml option to specify whether the grid renders error text (e.RowError) as HTML or as text.
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="ObjectDataSource1" KeyFieldName="Id" OnRowValidating="grid_RowValidating" ...>
<Columns>
...
</Columns>
<SettingsBehavior EncodeErrorHtml="true" />
</dx:ASPxGridView>
protected void grid_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e) {
foreach (GridViewColumn row in grid.Columns) {
GridViewDataColumn dataRow = row as GridViewDataColumn;
if (dataRow == null) continue;
if (e.NewValues[dataRow.FieldName] == null)
e.Errors[dataRow] = "Value cannot be null.";
}
if (e.NewValues["FirstName"] != null &&
e.NewValues["FirstName"].ToString().Length < 6) {
e.Errors[(GridViewDataColumn)grid.Columns["FirstName"]] = "Field value must be at least six characters long.";
}
if (e.Errors.Count > 0) e.RowError = "Please fill in all fields.";
}
You can use the HtmlRowPrepared event to indicate rows with invalid data. In the following sample, rows with invalid data are colored in red:
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="ObjectDataSource1" KeyFieldName="Id" OnHtmlRowPrepared="grid_HtmlRowPrepared" ...>
<Columns>
...
</Columns>
</dx:ASPxGridView>
protected void grid_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e) {
if(!object.Equals(e.RowType, GridViewRowType.Data)) return;
bool hasError = string.IsNullOrEmpty(e.GetValue("FirstName").ToString());
hasError = hasError || string.IsNullOrEmpty(e.GetValue("LastName").ToString());
hasError = hasError || !e.GetValue("Email").ToString().Contains("@");
hasError = hasError || (int)e.GetValue("Age") < 18;
DateTime arrival = (DateTime)e.GetValue("ArrivalDate");
hasError = hasError || DateTime.Today.Year != arrival.Year || DateTime.Today.Month != arrival.Month;
if(hasError) {
e.Row.ForeColor = System.Drawing.Color.Red;
}
}
Validate Edit Cells
Use the following APIs to specify validation settings for individual edit cells:
- The EditProperties.ValidationSettings property provides access to an edit cell’s validation settings. For example, the ValidationSettings.RequiredField property allows you to specify that a field is required.
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="ObjectDataSource1" KeyFieldName="Id" ...>
<Columns>
<dx:GridViewDataTextColumn Caption="First Name" FieldName="FirstName">
<PropertiesTextEdit>
<ValidationSettings>
<RequiredField IsRequired="true" ErrorText="Custom Error Text" />
</ValidationSettings>
</PropertiesTextEdit>
</dx:GridViewDataTextColumn>
...
</Columns>
...
</dx:ASPxGridView>
- The Validation event allows you to validate an edit cell’s value.
<dx:ASPxGridView ID="grid" runat="server" DataSourceID="ObjectDataSource1" KeyFieldName="Id" ...>
<Columns>
<dx:GridViewDataTextColumn Caption="First Name" FieldName="FirstName">
<PropertiesTextEdit ClientInstanceName="firstName">
<ClientSideEvents Validation="onValidation" />
</PropertiesTextEdit>
</dx:GridViewDataTextColumn>
...
</Columns>
...
</dx:ASPxGridView>
function onValidation(s, e) {
if (firstName.GetValue() == 'test') {
e.isValid = false;
e.errorText = "Invalid value";
}
Custom Validation
Use the EnableCustomValidation property to validate an edit cell’s value in a custom way.
<dx:ASPxGridView ID="grid" runat="server" ...>
<Columns>
...
<dx:GridViewDataComboBoxColumn FieldName="CategoryID" Caption="Category Name">
<PropertiesComboBox ClientInstanceName="comboBox" TextField="CategoryName" ...>
<ValidationSettings EnableCustomValidation="true" ValidateOnLeave="false" />
<ClientSideEvents TextChanged="onChanged" />
</PropertiesComboBox>
</dx:GridViewDataComboBoxColumn>
...
</Columns>
</dx:ASPxGridView>
function onChanged(s, e) {
if (comboBox.GetText() == 'Produce') {
comboBox.SetIsValid(false);
comboBox.SetErrorText('invalid value');
}
}
Validate Edit Form (Template)
Handle the RowValidating event to validate custom editor values in the edit form template on the server side.
<dx:ASPxGridView ID="grid" runat="server" OnRowValidating="grid_RowValidating" ...>
<Columns>
...
</Columns>
<Templates>
<EditForm>
<dx:ASPxMemo runat="server" ID="notesEditor" ... />
</EditForm>
</Templates>
</dx:ASPxGridView>
protected void grid_RowValidating(object sender, ASPxDataValidationEventArgs e)
{
ASPxMemo memo = ASPxCardView1.FindEditFormTemplateControl("notesEditor") as ASPxMemo;
if (memo.Text == "")
e.CardError = "Please fill in the notes.";
}
The grid sends the ‘UPDATEEDIT’ callback to the server and does not validate custom editors in edit form templates on the client side when a user clicks the “Update” button. In this case, use the template container’s ValidationGroup property (GridViewEditFormTemplateContainer.ValidationGroup or GridViewEditItemTemplateContainer.ValidationGroup) to validate custom editors on the client side. You can assign this property value to a custom editor’s ValidationSettings.ValidationGroup property.
On the “Update” button click:
<Templates>
<EditForm>
<dx:ASPxTextBox ID="ASPxTextBox1" runat="server" Width="170px" >
<ValidationSettings ValidationGroup="<%# Container.ValidationGroup %>">
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
<dx:ASPxGridViewTemplateReplacement ReplacementType="EditFormUpdateButton" runat="server" />
</EditForm>
</Templates>
Custom editors in the ASPxFormLayout:
<Templates>
<EditForm>
<dx:ASPxFormLayout ID="ASPxFormLayout1" runat="server" >
<Items>
<dx:LayoutItem Caption="First Name" FieldName="FirstName" >
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer ID="LayoutItemNestedControlContainer5" runat="server">
<dx:ASPxTextBox ID="ASPxFormLayout1_E2" runat="server" Width="170px" Text='<%# Eval("FIELD_NAME") %>' >
<ValidationSettings ValidationGroup='<%# (Container.NamingContainer as GridViewEditFormTemplateContainer).ValidationGroup %>'>
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
</Items>
.....
</dx:ASPxFormLayout>
</EditForm>
</Templates>
On an external button click:
<dx:ASPxGridView ID="grid" runat="server" ...>
<Columns>
...
</Columns>
<Templates>
<EditForm>
<div style="padding: 4px 3px 4px">
<dx:ASPxPageControl runat="server" ID="pageControl" Width="100%">
<TabPages>
<dx:TabPage Text="Info" Visible="true">
...
</dx:TabPage>
<dx:TabPage Text="Additional Info" Visible="true">
<ContentCollection>
<dx:ContentControl runat="server">
<dx:ASPxLabel runat="server" ID="label1" Text="Title:"></dx:ASPxLabel>
<br />
<dx:ASPxTextBox runat="server" ID="title" Text='<%# Eval("Title")%>' Width="30%" Height="20px" >
<ValidationSettings ValidateOnLeave="false" ValidationGroup="template">
<RequiredField IsRequired="true" ErrorText="This field is required" />
</ValidationSettings>
</dx:ASPxTextBox>
<br />
<dx:ASPxLabel runat="server" ID="label2" Text="Notes:"></dx:ASPxLabel>
<br />
<dx:ASPxMemo runat="server" ID="notesEditor" Text='<%# Eval("Notes")%>' Width="100%" Height="50px" ClientInstanceName="fg">
<ValidationSettings ValidateOnLeave="false" ValidationGroup="template">
<RequiredField IsRequired="true" ErrorText="This field is required" />
</ValidationSettings>
</dx:ASPxMemo>
</dx:ContentControl>
</ContentCollection>
</dx:TabPage>
</TabPages>
</dx:ASPxPageControl>
</div>
...
</EditForm>
</Templates>
</dx:ASPxGridView>
<br />
<dx:ASPxButton runat="server" Text="Validate" AutoPostBack="false">
<ClientSideEvents Click="OnClick" />
</dx:ASPxButton>
function OnClick(s, e) {
ASPxClientEdit.ValidateGroup('template');
}