New to Telerik UI for ASP.NET AJAX? Download free 30-day trial

Validation

In order to validate the input in RadGrid when editing and inserting records, you could use a combination of the ValidationSettings properties exposed by the control and validation controls added to make the validation in RadGrid more flexible.

Validation settings

RadGrid exposes the ValidationSettings class to give you control over the validation on submit inside the control. The available properties are:

  • EnableValidation - A boolean value indicating whether the grid values should be validated upon submit. Defaults to true.

  • CommandsToValidate - An array of string used to list the names of the commands which will trigger validation in RadGrid. By default, they are "PerformInsert, Update".

  • EnableModelValidation - A boolean value indicating whether model validation should be enabled.

  • ValidationGroup - A property used to set a ValidationGroup for the grid control, so that it is validated only along a certain group of controls having the same group name. By default, the grid does not have a validation group set, so if you set one for your validators, make sure to set it for the grid as well.

Adding a validator to an edit field in Telerik RadGrid

RadGrid provides an easy way to add required field validators to your generated input controls in Edit mode. This feature is applicable to:

  • GridBoundColumn

  • GridNumericColumn

  • GridHTMLEditorColumn

  • GridDropDownColumn

  • GridDateTimeColumn

The ColumnValidationSettings property is used to control validation of a given column editor via autogenerated RequiredFieldValidator and ModelBinding ModelErrorMessage control. This property is read-only, however, you can set the properties of the ColumnValidationSettings object it returns.

The properties can be set either declaratively or programmatically:

<telerik:GridBoundColumn DataField="ShipName" HeaderText="ShipName" UniqueName="ShipName">
    <ColumnValidationSettings EnableRequiredFieldValidation="true" EnableModelErrorMessageValidation="true">
        <RequiredFieldValidator ForeColor="Red" ErrorMessage="This field is required"></RequiredFieldValidator>
        <ModelErrorMessage BackColor="Red" />
    </ColumnValidationSettings>
</telerik:GridBoundColumn>

ModelErrorMessage control validation is available only in the Assemblies targetting the .NET 4.5 (e.g. Telerik version xxxx.x.xxx.45) when ModelBinding is used. See Included Assemblies

Adding a validator explicitly

In order to prevent the update operation if the user enters data in an edit field which is not in the correct format, you can wire the ItemCreated event of the grid to add a validator of your choice. There are four stages which need to be passed:

  1. Check whether the current item is in edit mode;

  2. Obtain reference to the respective GridColumnEditor instance and the editing control inside it;

  3. Create the validator and set its ControlToValidate property to point to the editing control;

  4. Add the validator to the Controls collection of the editing control Parent.

Below are the code snippets of an example in which we add RequiredFieldValidator to the TextBox editor of GridBoundColumn.

<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server" AutoGenerateColumns="False">
  <MasterTableView>
    <Columns>
      <telerik:GridBoundColumn UniqueName="ContactName" HeaderText="ContactName" DataField="ContactName">
      </telerik:GridBoundColumn>
      <telerik:GridEditCommandColumn UniqueName="EditCommandColumn">
      </telerik:GridEditCommandColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        GridEditableItem item = e.Item as GridEditableItem;
        GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("ContactName");
        TableCell cell = (TableCell)editor.TextBoxControl.Parent;

        RequiredFieldValidator validator = new RequiredFieldValidator();

        validator.ControlToValidate = editor.TextBoxControl.ID;
        validator.ErrorMessage = "*";
        cell.Controls.Add(validator);
    }
}
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs)
    If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then
        Dim item As GridEditableItem = CType(e.Item, GridEditableItem)
        Dim editor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("ContactName"), GridTextBoxColumnEditor)
        Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
        Dim validator As RequiredFieldValidator = New RequiredFieldValidator
        validator.ControlToValidate = editor.TextBoxControl.ID
        validator.ErrorMessage = "*"
        cell.Controls.Add(validator)
    End If
End Sub

With version older than Q1 2013 you should use the code snippet below to add RequiredFieldValidator to the TextBox editor of GridBoundColumn

<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server" AutoGenerateColumns="False">
  <MasterTableView>
    <Columns>
      <telerik:GridBoundColumn UniqueName="ContactName" HeaderText="ContactName" DataField="ContactName">
      </telerik:GridBoundColumn>
      <telerik:GridEditCommandColumn UniqueName="EditCommandColumn">
      </telerik:GridEditCommandColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        GridEditableItem item = e.Item as GridEditableItem;
        GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("ContactName");
        TableCell cell = (TableCell)editor.TextBoxControl.Parent;

        RequiredFieldValidator validator = new RequiredFieldValidator();
        editor.TextBoxControl.ID = "ID_for_validation";
        validator.ControlToValidate = editor.TextBoxControl.ID;
        validator.ErrorMessage = "*";
        cell.Controls.Add(validator);
    }
}
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs)
    If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then
        Dim item As GridEditableItem = CType(e.Item, GridEditableItem)
        Dim editor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("ContactName"), GridTextBoxColumnEditor)
        Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
        Dim validator As RequiredFieldValidator = New RequiredFieldValidator
        editor.TextBoxControl.ID = "ID_for_validation"
        validator.ControlToValidate = editor.TextBoxControl.ID
        validator.ErrorMessage = "*"
        cell.Controls.Add(validator)
    End If
End Sub

Adding a custom validator explicitly

In order to prevent the update operation if the user enters data in an edit field which is not in the correct format, you can wire the ItemCreated event of the grid to add a validator of your choice. These steps will guide you through this process:

  1. Check whether the current item is in edit mode;

  2. Obtain reference to the respective GridColumnEditor instance and the editing control inside it;

  3. Create the validator and set its ControlToValidate property to point to the editing control;

  4. Enable the ValidateEmptyText property of the validator if you prefer to check for empty inputs as well;

  5. Set the ClientValidationFunction;

  6. Subscribe to the ServerValidate event;

  7. Optionally, you can set the ValidationGroup to separate the validation logic of the insert, edit or multiple edit forms;

  8. Add the validator to the Controls collection of the editing control Parent;

Below are the code snippets of an example in which we add CustomValidator to the TextBox editor of GridBoundColumn. If the new value does not contain the letter a, the validation will fail on client-side. And if the new value does not contain the letter b, the validation will fail this time on server-side.

<telerik:GridBoundColumn DataField="ShipName"
    FilterControlAltText="Filter ShipName column" HeaderText="ShipName"
    SortExpression="ShipName" UniqueName="ShipName">
</telerik:GridBoundColumn>
function shipNameValidation(valEl, args) {
    // validate on client-side
    args.IsValid = args.Value.includes("a");
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
    if (e.Item.IsInEditMode)
    {
        GridEditableItem item = e.Item as GridEditableItem;
        GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("ShipName");
        TableCell cell = (TableCell)editor.TextBoxControl.Parent;

        CustomValidator validator = new CustomValidator()
        {
            ID = "CustomValidatorShipName",
            ControlToValidate = editor.TextBoxControl.ID,
            ValidateEmptyText = true,
            ErrorMessage = "* Cannot be empty and should contain a and b",
            ForeColor = Color.OrangeRed,
            ClientValidationFunction = "shipNameValidation",
            ValidationGroup = editor.TextBoxControl.UniqueID
        };
        validator.ServerValidate += CustomValidatorShipName_ServerValidate;

        // prevent insert and edit forms to validate each other
        // this button can also be of type Button, ImageButton or LinkButton depending on the following property:
        // RadGrid1.MasterTableView.EditFormSettings.EditColumn.ButtonType = GridButtonColumnType.FontIconButton; (default)
        string buttonName = item is IGridInsertItem ? "PerformInsertButton" : "UpdateButton";
        (item.FindControl(buttonName) as ElasticButton).ValidationGroup = editor.TextBoxControl.UniqueID;

        cell.Controls.Add(validator);
    }
}
private void CustomValidatorShipName_ServerValidate(object source, ServerValidateEventArgs args)
{
    // validate on server-side
    args.IsValid = args.Value.Contains("b");
}
Protected Sub RadGrid1_ItemCreated(sender As Object, e As GridItemEventArgs)
    If e.Item.IsInEditMode Then
        Dim item As GridEditableItem = TryCast(e.Item, GridEditableItem)
        Dim editor As GridTextBoxColumnEditor = CType(item.EditManager.GetColumnEditor("ShipName"), GridTextBoxColumnEditor)
        Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
        Dim validator As CustomValidator = New CustomValidator() With {
            .ID = "CustomValidatorShipName",
            .ControlToValidate = editor.TextBoxControl.ID,
            .ValidateEmptyText = True,
            .ErrorMessage = "* Cannot be empty and should contain a and b",
            .ForeColor = Color.OrangeRed,
            .ClientValidationFunction = "shipNameValidation",
            .ValidationGroup = editor.TextBoxControl.UniqueID
        }
        AddHandler validator.ServerValidate, AddressOf CustomValidatorShipName_ServerValidate

        ' prevent insert And edit forms to validate each other
        ' this button can also be of type Button, ImageButton Or LinkButton depending on the following property:
        ' RadGrid1.MasterTableView.EditFormSettings.EditColumn.ButtonType = GridButtonColumnType.FontIconButton; (default)
        Dim buttonName As String = If(TypeOf item Is IGridInsertItem, "PerformInsertButton", "UpdateButton")
        TryCast(item.FindControl(buttonName), ElasticButton).ValidationGroup = editor.TextBoxControl.UniqueID
        cell.Controls.Add(validator)
    End If
End Sub
Protected Sub CustomValidatorShipName_ServerValidate(source As Object, args As ServerValidateEventArgs)
    ' validate on server-side
    args.IsValid = args.Value.Contains("b")
End Sub

You can find a runnable web site sample in the Add Custom Validator Explicitly for RadGrid Editing Code-Library.

Adding a validator to EditItemTemplate of GridTemplateColumn

The approach is the same as with the standard MS DataGrid control. You can place the respective validator in the EditItemTemplate of your GridTemplateColumn and relate its ControlToValidate property with the ID of the control you would like to validate. In the forthcoming sample the RequiredFieldValidator control will validate the TextBox control inside the EditItemTemplate:

<telerik:RadGrid RenderMode="Lightweight" ID="RadGrid1" runat="server">
  <MasterTableView AutoGenerateColumns="False">
    <Columns>
      <telerik:GridTemplateColumn HeaderText="ContactName" UniqueName="TemplateColumn">
        <EditItemTemplate>
          <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ContactName") %>'></asp:TextBox>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
            ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
        </EditItemTemplate>
        <ItemTemplate>
          <asp:Label ID="Label1" runat="server" Text='<%# Eval("ContactName") %>'></asp:Label>
        </ItemTemplate>
      </telerik:GridTemplateColumn>
      <telerik:GridEditCommandColumn UniqueName="EditCommandColumn">
      </telerik:GridEditCommandColumn>
    </Columns>
  </MasterTableView>
</telerik:RadGrid>

Server-side validationIn some scenarios you may want to disable the client-side validation for the grid input and perform the whole validation process server-side.Here is a sample means to perform server-side validation using CustomValidator and its ServerValidate event (the validator error message will be displayed when the user enters string in the textbox with ID=TextBox1 which starts with X character):

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("DataItem.Country") %>'>
</asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid input"
  ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
    if (args.Value.StartsWith("X"))
    {
        args.IsValid = false;
    }
}
protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
    if (e.CommandName == RadGrid.UpdateCommandName)
    {
        if (!Page.IsValid)
        {
            e.Canceled = true;
        }
    }
}
Protected Sub CustomValidator1_ServerValidate(ByVal [source] As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
    If args.Value.StartsWith("X") Then
        args.IsValid = False
    End If
End Sub 'CustomValidator1_ServerValidate

Protected Sub RadGrid1_ItemCommand(ByVal [source] As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
    If e.CommandName = RadGrid.UpdateCommandName Then
        If Not Page.IsValid Then
            e.Canceled = True
        End If
    End If
End Sub 'RadGrid1_ItemCommand

Custom validation For more complex/custom validation operations you can extend the default ASP.NET validation and integrate CustomValidator control inside your grid instance. Here is an online resource which gives an example of operating with CustomValidators and configuring them to validate the user input as per your requirements:https://aspnet.4guysfromrolla.com/articles/073102-1.aspx

In this article