Edit this page

Validating

One of the most important features provided by RadGridView is the data validation. Data validation features enable you to take complete control of the data entered in your grid's cells.

The purpose of this tutorial is to show you how to validate data using RadGridView. The following cases will be discussed:

The data validation is controllable through events. Be sure you are familiar with all validation events exposed by the RadGridView.

For the purpose of this tutorial, we will use the RadGridView declaration in Example 1. The RadGridView is populated with some sample data.

[XAML] Example 1: Declare RadGridView.

<telerik:RadGridView x:Name="radGridView"/>

Figure 1: Standard appearance of RadGridView.

Setting the mode for the validation

RadGridView exposes a property - ValidatesOnDataErrors - that controls the way the data validation, provided by IDataErrorInfo and INotifyDataErrorInfo Interfaces, is performed. It may be set to one of the following values:

  • None: Denotes that RadGridView will not perform any validation.

  • InViewMode: Denotes that RadGridView will perform validation only in view mode.

  • InEditMode: Denotes that RadGridView will perform validation only in edit mode, i.e., when the cell is leaving edit mode. In case the RadGridView is initially loaded with incorrect value, no error messages will be displayed.

  • Default: This is the default value. It combines the two previous ones - InViewMode | InEditMode.

Setting the ValidateOnDataErrors property will not affect the UI validation provided by the CellValidating and RowValidating events.

Setting the Validation Type

In R2 2016, Telerik introduced the ValidationType property of RadGridView. It provides you with the possibility to choose what type of validation to apply for each instance of RadGridView. It is a Flags Enumeration and can take the following values:

  • None: None of the validation mechanisms is respected.
  • DataAnnotations: Only validation through data annotations is respected.
  • IDataErrorInfo: Only validation through the IDataErrorInfo interface is respected.
  • INotifyDataErrorInfo: Only validation through the INotifyDataErrorInfo interface is respected.
  • Default: Validation through all three mechanisms is respected.

[XAML] Example 2: Set the ValidationType property of RadGridView.

    <telerik:RadGridView x:Name="radGridView" ValidationType="Default"/>

Validating Data on a Cell Level

The cell validation occurs when a GridViewCell is edited and its new data is about to be committed. At this moment, a CellValidating event is fired and since the new value is not committed yet to the underlying data object, here is the perfect place for applying a custom UI validation.

Example 3 shows how to validate the OrderNo property of the Order object to be longer than 5 characters.

Attach to the CellValidating event, which is exposed by the RadGridView.

[XAML] Example 3: Attach to the CellValidating event.

<telerik:RadGridView CellValidating="radGridView_CellValidating"/>

Switch to the code-behind and add your custom validation logic in the event handler.

[C#] Example 3: Add custom logic in the code behind.

private void radGridView_CellValidating(object sender, Telerik.Windows.Controls.GridViewCellValidatingEventArgs e)
{
    if (e.Cell.Column.UniqueName == "OrderNO")
    {
        if (e.NewValue.ToString().Length < 5)
        {
            e.IsValid = false;
            e.ErrorMessage = "OrderNO must be longer than five characters.";
        }
    }
}

[VB.NET] Example 3: Add custom logic in the code behind.

Private Sub radGridView_CellValidating(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.GridViewCellValidatingEventArgs)
    If e.Cell.Column.UniqueName = "OrderNO" Then
        If e.NewValue.ToString().Length < 5 Then
            e.IsValid = False
            e.ErrorMessage = "OrderNO must be longer than five characters."
        End If
    End If
End Sub

When you try to enter an order number that has fewer than five characters, you should see a validation message that is similar to Figure 2.

Figure 2: RadGridView`s appearance after validation.

When you set the e.IsValid property to False, this will cancel the editing process and will return focus to the invalid GridViewCell. After this UI layer validation is successful (e.IsValid is True, which is the default value). Then the Data layer validation occurs. This is the validation that is built into the business object implementation.

Validating Data on a Property Level

An alternative approach is to use validation on a property level as shown in Example 4. In this case, you need to throw an exception when an incorrect value is about to be set. This results in a binding validation error (Figure 3) and the GridViewBoundColumnBase editor will enter into an invalid state.

[C#] Example 4: Set validation on a property level.

public class Order
{
    private string orderNo;
    public string OrderNO
    {
        get
        {
            return this.orderNo;
        }
        set
        {
            if (value.Length < 5)
            {
                throw new Exception("OrderNo should be longer than 5 characters.");
            }
            this.orderNo = value;
        }
    }

    public int Total { get; internal set; }
}

[VB.NET] Example 4: Set validation on a property level.

Public Class Order
    Private m_orderNo As String

    Public Property OrderNO() As String
        Get
            Return Me.m_orderNo
        End Get
        Set(ByVal value As String)
            If value.Length < 5 Then
                Throw New Exception("OrderNo should be longer than 5 characters.")
            End If
            Me.m_orderNo = value
        End Set
    End Property

    Public Property Total As Integer
End Class

Figure 3: RadGridView`s appearance after validation:

An exception of any kind will result in a validation error, and an exception message will appear as an error tooltip.

Validating Data on a Row Level

In the previous examples, the data was validated per cell, using the CellValidating event or property validation. You can do the same thing per row, using the RowValidating event. The RowValidating event is very similar to the CellValidating event. However, instead of getting an individual cell, you are getting an entire row.

Example 5 shows how to validate the OrderNO and Total properties of the Order object.

Attach to the RowValidating event, which is exposed by the RadGridView.

[XAML] Example 5: Attach to the RowValidating event.

<telerik:RadGridView RowValidating="radGridView_RowValidating"/>

Switch to the code-behind and add your custom validation logic in the event handler.

[C#] Example 5: Apply custom logic in the RowValidating event.

private void radGridView_RowValidating(object sender, Telerik.Windows.Controls.GridViewRowValidatingEventArgs e)
{

    Order order = e.Row.DataContext as Order;
    if (String.IsNullOrEmpty(order.OrderNO) || order.OrderNO.Length < 5)
    {
        GridViewCellValidationResult validationResult = new GridViewCellValidationResult();
        validationResult.PropertyName = "OrderNO";
        validationResult.ErrorMessage = "OrderNO is required and must be at least five characters";
        e.ValidationResults.Add(validationResult);
        e.IsValid = false;
    }

    if (order.Total < 0)
    {
        GridViewCellValidationResult validationResult = new GridViewCellValidationResult();
        validationResult.PropertyName = "Total";
        validationResult.ErrorMessage = "Total must be positive";
        e.ValidationResults.Add(validationResult);
        e.IsValid = false;
    }
}

[VB.NET] Example 5: Apply custom logic in the RowValidating event.

Private Sub radGridView_RowValidating(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.GridViewRowValidatingEventArgs)
    Dim order As Order = TryCast(e.Row.DataContext, Order)
    If [String].IsNullOrEmpty(order.OrderNO) OrElse order.OrderNO.Length < 5 Then
        Dim validationResult As New GridViewCellValidationResult()
        validationResult.PropertyName = "OrderNO"
        validationResult.ErrorMessage = "OrderNO is required and must be at least five characters"
        e.ValidationResults.Add(validationResult)
        e.IsValid = False
    End If
    If order.Total < 0 Then
        Dim validationResult As New GridViewCellValidationResult()
        validationResult.PropertyName = "Total"
        validationResult.ErrorMessage = "Total must be positive"
        e.ValidationResults.Add(validationResult)
        e.IsValid = False
    End If
End Sub

Two things worth mentioning here:

  • In order to access the new values, you should grab the row's DataContext (in this case, it is an Order). For the old values, use the OldValues property.

  • The GridViewCellValidationResult object is used for displaying error messages when the user enters wrong data.

Figure 4 shows the result from a failed validation.

Figure 4: RadGridView`s appearance after validation on row level was applied.

Once you have added such errors, you will have to explicitly clear them when needed. Please check this help article for information about how to clear user defined errors.

You can check this troubleshooting article on how to clear user defined errors.

<

Validating Data Through Data Annotations

With the Silverlight platform, you can take advantage of the System.ComponentModel.DataAnnotations assembly. The following code snippet demonstrates how to use data annotation attributes to validate a property value (again within the property setter). It is even better when you use RIA services, since this code will be automatically added for you by the RIA Service's code generator.

The code snippet below shows you how to use DataAnnotations in order to validate the OrderNO property of the Order object.

[C#] Example 5: Set validation through data DataAnnotations.

[Required]
public string OrderNO
{
    get
    {
        return this.orderNo;
    }
    set
    {
        ValidationContext validationContext = new ValidationContext(this, null, null);
        validationContext.MemberName = "OrderNO";
        Validator.ValidateProperty(value, validationContext);
        this.orderNo = value;
    }
}

[VB.NET] Example 5: Set validation through data DataAnnotations.

<Required()>
Public Property OrderNO() As String
    Get
        Return Me.m_orderNo
    End Get
    Set(ByVal value As String)
        Dim validationContext As New ValidationContext(Me, Nothing, Nothing)
        validationContext.MemberName = "OrderNO"
        Validator.ValidateProperty(value, validationContext)
        Me.m_orderNo = value
    End Set
End Property

In order to use DataAnnotations you should add a reference to the System.ComponentModel.DataAnnotations assembly.

The following Validation Attributes are available:

  • RequiredAttribute: Specifies that a value must be provided for a property.

  • RegularExpressionAttribute: Designates a regular expression to be used for validation of the associated member.

  • StringLengthAttribute: Specifies the maximum and minimum number of characters that are allowed for an entity member.

  • RangeAttribute: Designates the minimum and maximum constraints for the associated member.

  • DateTypeAttribute: Specifies the name of an additional type to associate with an entity member.

  • CustomValidationAttribute: Designates a customized method to execute to validate the entity member.

You can see the result in Figure 5.

Figure 5: Appearance of RadGridView after DataAnnotations valididation was applied.

radgridview managing data validation 050

Once the UI and Data validation is passed (i.e., the Binding tried to update the value for the bound property), the CellValidated event is raised. The ValidationResult can be valid or not. Here you can also add a custom logic like changing the visual state of the editor (through the e.EditorElement).

Examples

For a general example on how to validate the data, you can check our Validation
online demos.

You can also download runnable projects from our online SDK repository here; the examples are listed under GridView.

  • GridView/ValidationIDataErrorInfo.

  • GridView/ValidationINotifyDataErrorInfo.

Although GitHub is a very well-known platform, we saw a better and easier approach for reviewing our examples in our SDK Samples Browser. The SDK Samples Browser is an application that automatically connects to GitHub and downloads the XAML SDK repository locally to a location that could be set by the user. After download is complete, the application gives a very convenient navigation between all the available examples and a search functionality that doesn’t simply search by control’s names but also through the example’s names and descriptions.

See Also