This is a migrated thread and some comments may be shown as answers.

client side validation in radgrid.

7 Answers 757 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Madhu
Top achievements
Rank 1
Madhu asked on 03 May 2012, 12:18 AM
Hi,
 I need to validate a control inside the radgrid (If empty show message). Here is what i have comeup with. But this doesn't seem to be working.
Thanks in advance


<%@ Page Title="" Language="VB" MasterPageFile="~/master/default.master" AutoEventWireup="false" CodeFile="SubProductOrSrvcAdminstration.aspx.vb" Inherits="EncoreBMF_SubProductOrSrvcAdminstration" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%@ Register assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" namespace="System.Web.UI.WebControls" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeaderContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
  
<style type="text/css">
div.ex
{
width:480px;
padding:10px;
border:2px solid gray;
margin:0px;
}
</style>
       <asp:ValidationSummary ID="ValidationSummary1" runat="server"  Enabled="true" ForeColor="Red" HeaderText="Errors:" 
        ShowSummary="true" DisplayMode="List" /> 
  
                <telerik:RadFormDecorator ID="FormDecorator1" runat="server" DecoratedControls="all">
                </telerik:RadFormDecorator>
                 <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"
                    <AjaxSettings
                        <telerik:AjaxSetting AjaxControlID="ValidationSummary1"
                            <UpdatedControls
                                <telerik:AjaxUpdatedControl ControlID="ValidationSummary1" /> 
                            </UpdatedControls
                        </telerik:AjaxSetting
                        <telerik:AjaxSetting AjaxControlID="rgSubProdOrSvc"
                            <UpdatedControls
                                <telerik:AjaxUpdatedControl ControlID="rgSubProdOrSvc" /> 
                            </UpdatedControls
                        </telerik:AjaxSetting
                    </AjaxSettings
                 </telerik:RadAjaxManager
                   
               <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"
                        <script type="text/javascript"
                                function clientSubsvcValidation(source, arguments) { 
                                    var currentCell = source.parentNode; 
                                    var currentRow = currentCell.parentNode 
                        
                                    //get a reference to the calling validator control 
                                    var CustomValidator1 = source.id; 
                                    
                                    //get the value of the GridBoundColumn 'salesperson'
                                    var SubSvcID;
                                    var SubSvcName;
                                    SubSvcID = $telerik.findElement(currentRow, CustomValidator1.replace('CustomValidator1', 'EncoreProductSubServiceId')).value
                                    SubSvcID = $telerik.findElement(currentRow, CustomValidator1.replace('CustomValidator1', 'SubServiceName')).value
                                
                        </script
    
               </telerik:RadCodeBlock
      
                            
                <div class="ex"> Sub-Products / Services Administration 
  
                        <hr runat="server" id="Hr1" style="border-color: #659EC7" />
                                                     
                                <br />
                                  
  
                                  
                                  <telerik:RadGrid ID="rgSubProdOrSvc" runat="server" GridLines="None" 
                                    DataSourceID="edsProductSubService"
                                    AutoGenerateColumns="False"
                                  >
                          
                                    <MasterTableView
                                        DataSourceID="edsProductSubService"
                                        DataKeyNames="EncoreProductSubServiceId"
                                        EditMode ="InPlace"
                                        AllowAutomaticInserts="false"
                                        AllowAutomaticUpdates="false"
                                        AllowAutomaticDeletes="false"
                                        CommandItemDisplay= "TopAndBottom"
                                    >
                                        <NoRecordsTemplate><div>Click on the plus(+)sign above to add a Sub-Product to the grid.</div></NoRecordsTemplate>
                                 
                                        <EditItemTemplate>
                                           
                                                 
                                            <asp:CheckBox ID="chkIsActive" runat="server"  Checked = '<%# Eval("IsActiveFlag") %>' />
                                                          
                                                    
                                             <asp:TextBox ID="txtsubSvcName" runat="server" Text='<%# Eval("SubServiceName") %>'></asp:TextBox>
                                             <asp:CustomValidator ID="CustomValidator1" ControlToValidate="txtsubSvcName" 
                                             ClientValidationFunction="clientSubsvcValidation" 
                                              Display="Dynamic" ErrorMessage="Not an even number!" 
                                             Text="Please enter a valid Sub-product name" Font-Name="verdana" Font-Size="10pt" 
                                             runat="server" />
                                        <%--  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtsubSvcName" ErrorMessage="Please enter a valid Sub-product name" Display="Dynamic" runat="server">*
                        </asp:RequiredFieldValidator>   OnServerValidate="ServerUnitPriceValidation" --%>
                                             <asp:TextBox ID="txtSvcShortName" runat="server" Text='<%# Eval("SubServiceShortName") %>'></asp:TextBox>
                                        </EditItemTemplate>
                                    <%-- <ItemTemplate>
                                         <asp:CheckBox  ID="chkIsActiveIT" runat="server" Checked='<%# Eval("IsActiveFlag") %>'></asp:CheckBox>
                                                        
                                                    
                                           <asp:Label ID="lblsubSvcName" runat="server" Text='<%# Eval("SubServiceName") %>'></asp:Label>
                                                             
                                            <asp:Label ID="lblsubSvcShortName" runat="server" Text='<%# Eval("SubServiceShortName") %>'></asp:Label>
                                     </ItemTemplate>--%>
                                       
  
                                          
                                        <CommandItemSettings ExportToPdfText="Export to Pdf" />
                                      <Columns>
                                                                        
                                         <telerik:GridEditCommandColumn >
                                         </telerik:GridEditCommandColumn>
                                         <telerik:GridCheckBoxColumn DataField="IsActiveFlag" HeaderText="Inactive" 
                                                UniqueName="Inactive">
                                                </telerik:GridCheckBoxColumn>
                                                <telerik:GridBoundColumn DataField="SubServiceName" 
                                                HeaderText="Sub-prod/svc Name" UniqueName="SubServiceName">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="SubServiceShortName" 
                                                HeaderText="Short Name" UniqueName="SubServiceShortName">
                                            </telerik:GridBoundColumn>
                                           
                                        </Columns>
                                        <EditFormSettings>
                                          <EditColumn UniqueName="EditCommandColumn1">
                                            </EditColumn>
                                            
                                              
                                        </EditFormSettings>
                                    </MasterTableView>
                                </telerik:RadGrid>
                                <asp:EntityDataSource ID="edsProductSubService" runat="server" 
                                    ConnectionString="name=Entities" DefaultContainerName="Entities" 
                                    EntitySetName="EncoreProductSubService" 
                                     Select="it.[EncoreProductSubServiceId], it.[IsActiveFlag], it.[SubServiceName], it.[SubServiceShortName] ">
                                      
                                </asp:EntityDataSource>
                                
                                <br />
                       <%-- </div>--%>
                                                                        
                                                         
                        <asp:LinkButton ID="lnkAddBundl" runat="server">Add Sub-prod / svc</asp:LinkButton>
                            
                        <br />
                    <br />
                    <br />
                    <br />
                        <br />
                        <br />
                </div>

7 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 03 May 2012, 01:42 PM
Hi Madhu,

I guess you want to show an empty message when the TextBox inside the EditItemTemplate is empty. You can easily achieve this by adding the RequiredFieldValidator .If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to require the user to enter data in the input control.Please check the following code snippet.

ASPX:
<EditItemTemplate>                                               
    <asp:CheckBox ID="chkIsActive" runat="server"  Checked = '<%# Eval("IsActiveFlag") %>' />                                               
    <asp:TextBox ID="txtsubSvcName" runat="server" Text='<%# Eval("SubServiceName") %>' ></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtsubSvcName" ErrorMessage="Please enter a valid name" Display="Dynamic" runat="server">*
    </asp:RequiredFieldValidator
    <asp:TextBox ID="txtSvcShortName" runat="server" Text='<%# Eval("SubServiceShortName") %>'></asp:TextBox>
</EditItemTemplate>

Thanks,
Princy.
0
Mayur
Top achievements
Rank 1
answered on 11 Oct 2013, 10:15 AM
Hello Sir,
              Hope you would be doing well. I am having same issue of validation. But I am not using TemplateColumn in RadGrid. I am just working with GridBoundColumnEditors which got TextBox in insert Mode and edit Mode. I am using InPlace Add and Update approach.

Now what I required is I want to validate all the TextBoxes with different conditions {like email,phone,numbers only, alphabates only etc...}
when ItemCommand is fired....
Can anybody help me out please ?
0
Princy
Top achievements
Rank 2
answered on 11 Oct 2013, 11:15 AM
Hi Mayur,

You can have client side validation as below for a BoundColumn.

ASPX:
<telerik:GridBoundColumn DataField="ShipCountry" HeaderText="ShipCountry" UniqueName="ShipCountry">
  <ColumnValidationSettings EnableRequiredFieldValidation="true">
   <RequiredFieldValidator ForeColor="Red" ErrorMessage="This field is required"></RequiredFieldValidator>
  </ColumnValidationSettings>
</telerik:GridBoundColumn>

Or you can have serverside validation as follows.

ASPX:
<telerik:GridBoundColumn UniqueName="OrderID" DataField="OrderID" HeaderText="OrderID">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="CustomerID" HeaderText="CustomerID" UniqueName="CustomerID">
</telerik:GridBoundColumn>

C#:
public void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        //RequiredFieldValidator
        GridEditableItem item = e.Item as GridEditableItem;
        RequiredFieldValidator validator = new RequiredFieldValidator();
        validator.ControlToValidate = ((TextBox)item["CustomerID"].Controls[0]).ID;
        validator.ErrorMessage = "*";
        validator.ForeColor = Color.Red;
        item["CustomerID"].Controls.Add(validator);
 
        //RegularExpressionValidator to enter only numbers
        GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("OrderID");        
        TableCell cell = (TableCell)editor.TextBoxControl.Parent;
        RegularExpressionValidator validate = new RegularExpressionValidator();
        validate.ControlToValidate = editor.TextBoxControl.ID;          
        validate.ValidationExpression = @"^(\d{1,7})\b";
        validate.ErrorMessage = "Enter Number";
        validate.ForeColor = Color.Red;
        cell.Controls.Add(validate);
    }
}

Thanks,
Princy
0
Mayur
Top achievements
Rank 1
answered on 12 Oct 2013, 07:11 AM
Hi Princy,
              Thank you very much for giving me the code. But it is not working at my end. I am not sure if i am missing something or else i need to change something in my code.
Please find my code snapshot below for your reference and tell me what changes i have to made.

Senarios:  I am using RadGrid and i am doing CRUD operations from code behind though Item COmmand event. but before CRUD operations i need to validate my grid controls for input validations like email, numbers, pin code etc..... In my code behind I am calling WCF service to save,update and delete data to database.

Here is my code...

aspx
------
<telerik:RadGrid ID="dgExpenseHead" GridLines="None" runat="server" AllowAutomaticDeletes="False"
                        AllowAutomaticInserts="False" AllowAutomaticUpdates="False" AllowPaging="True"
                        AutoGenerateColumns="False" OnPreRender="dgExpenseHead_PreRender" CellSpacing="0"
                        OnNeedDataSource="dgExpenseHead_NeedDataSource" OnItemCommand="dgExpenseHead_ItemCommand"
                        OnItemDataBound="dgExpenseHead_ItemDataBound" 
                        onitemcreated="dgExpenseHead_ItemCreated">
                        <PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
                        <MasterTableView Width="100%" CommandItemDisplay="TopAndBottom" HorizontalAlign="NotSet"
                            AutoGenerateColumns="False" EditMode="InPlace" DataKeyNames="ExpenseHeadID" UseAllDataFields="true">
                            <Columns>
                                <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"
                                    HeaderText="Control">
                                    <ItemStyle CssClass="MyImageButton"></ItemStyle>
                                </telerik:GridEditCommandColumn>
                                <telerik:GridTemplateColumn UniqueName="SNo" HeaderText="S.No." Visible="false">
                                    <ItemTemplate>
                                        <asp:Label runat="server" ID="lblSNo" Text='<%# Container.ItemIndex +1%>'></asp:Label>
                                    </ItemTemplate>
                                </telerik:GridTemplateColumn>
                                <telerik:GridBoundColumn DataField="ExpenseHeadDescription" HeaderText="ExpenseHeadDescription"
                                    SortExpression="ExpenseHeadDescription" UniqueName="ExpenseHeadDescription" ColumnEditorID="txtExpenseHeadDescriptionEditor">
                                </telerik:GridBoundColumn>
                                <telerik:GridCheckBoxColumn DataField="ExpenseHeadActive" HeaderText="Active" SortExpression="ExpenseHeadActive"
                                    UniqueName="ExpenseHeadActive" EditFormColumnIndex="1" DataType="System.Boolean">
                                </telerik:GridCheckBoxColumn>
                                <telerik:GridButtonColumn ConfirmText="Delete this expense head?" ConfirmDialogType="RadWindow"
                                    Visible="true" ConfirmTitle="Delete" ButtonType="ImageButton" CommandName="Delete"
                                    Text="Delete" UniqueName="DeleteColumn">
                                    <ItemStyle HorizontalAlign="Center" CssClass="MyImageButton"></ItemStyle>
                                </telerik:GridButtonColumn>
                            </Columns>
                            <CommandItemSettings ExportToPdfText="Export to PDF" />
                            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
                            </RowIndicatorColumn>
                            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
                            </ExpandCollapseColumn>
                            <EditFormSettings ColumnNumber="2" CaptionDataField="ExpenseHeadDescription" CaptionFormatString="Edit properties of Expsense Head {0}"
                                InsertCaption="New Expense Head">
                                <FormTableItemStyle Wrap="False"></FormTableItemStyle>
                                <FormCaptionStyle CssClass="EditFormHeader"></FormCaptionStyle>
                                <FormMainTableStyle GridLines="None" CellSpacing="0" CellPadding="3" Width="100%">
                                </FormMainTableStyle>
                                <FormTableStyle CellSpacing="0" CellPadding="2" Height="110px"></FormTableStyle>
                                <FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>
                                <FormTableButtonRowStyle HorizontalAlign="Right" CssClass="EditFormButtonRow"></FormTableButtonRowStyle>
                            </EditFormSettings>
                        </MasterTableView>
                        <ExportSettings FileName="ExpenseHead" IgnorePaging="true" ExportOnlyData="true"
                            Excel-Format="ExcelML" OpenInNewWindow="true">
                        </ExportSettings>
                    </telerik:RadGrid>


CS:
-----

protected void dgExpenseHead_ItemCreated(object sender, GridItemEventArgs e)
        {
            if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
            {
                //RequiredFieldValidator
                GridEditableItem item = e.Item as GridEditableItem;
                RequiredFieldValidator validator = new RequiredFieldValidator();
                validator.ControlToValidate = ((TextBox)item["ExpenseHeadDescription"].Controls[0]).ID;
                validator.ErrorMessage = "*";
                validator.ForeColor = Color.Red;
                item["ExpenseHeadDescription"].Controls.Add(validator);
            }
        }
0
Antonio Stoilkov
Telerik team
answered on 16 Oct 2013, 07:47 AM
Hi Mayur,

The experienced problem could be caused from the fact that you are using a RadControls version older than Q1 2013 as described in detail in the help article below. If this is the case you could use the code provided below.
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);
    }
}

Regards,
Antonio Stoilkov
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Mayur
Top achievements
Rank 1
answered on 23 Oct 2013, 06:47 AM
Hi Antonio Stoilkov,
                                     Thank you very much. This code is working fine. Can you also send me the code in above case for validating DropDownList or ListBox control. I mean in just above case if the control os of DropDownList or ListBox control how i should validate it.

<telerik:GridTemplateColumn HeaderText="State" DataField="StateName" UniqueName="StateName">
                                    <ItemTemplate>
                                        <%# DataBinder.Eval(Container.DataItem, "StateName")%>
                                    </ItemTemplate>
                                </telerik:GridTemplateColumn>

Here is my aspx code
0
Princy
Top achievements
Rank 2
answered on 24 Oct 2013, 11:02 AM
Hi Mayur,

You can add the validation at the aspx as follows:

ASPX:
<telerik:GridTemplateColumn HeaderText="StateName" DataField="StateName" UniqueName="StateName">
    <ItemTemplate>
        <%# DataBinder.Eval(Container.DataItem, "StateName")%>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
            DataTextField="StateName" DataValueField="StateName" >
        </asp:DropDownList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
            ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
    </EditItemTemplate>
</telerik:GridTemplateColumn>

Thanks,
Princy
Tags
Grid
Asked by
Madhu
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Mayur
Top achievements
Rank 1
Antonio Stoilkov
Telerik team
Share this question
or