Home > Software design >  I want to make a required field validator for each text box having blank spaces in gridview using ja
I want to make a required field validator for each text box having blank spaces in gridview using ja

Time:01-13

<div style="height: 500px; overflow: scroll;" id="divEmployee" runat="server">
   <asp:GridView ID="gView" runat="server" AllowPaging="false"
      AutoGenerateColumns="False" CssClass="LabelText" DataKeyNames="Id"
      EmptyDataText="No Data Found !" EnableModelValidation="True"
      OnRowEditing="gView_RowEditing" Width="100%">
      <HeaderStyle CssClass="GridHeader" Height="30px" />
      <PagerStyle CssClass="GridRowPage" Font-Size="10pt" />
      <RowStyle CssClass="NormalGridRow" Height="30px" />
      <FooterStyle CssClass="GridHeader" />
      <Columns>
         <asp:BoundField DataField="Id"
            HeaderStyle-HorizontalAlign="Center" HeaderText="ID"
            ItemStyle-HorizontalAlign="Left">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Left" />
         </asp:BoundField>
         <%--  
            <asp:TemplateField HeaderText="Id" SortExpression="" Visible="true">
                <ItemTemplate>
                    <asp:Label ID="lblEmployeeCode" runat="server" SkinID="NoColor" Text='<%# Bind("Id") %>'>
                    </asp:Label>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
            </asp:TemplateField>--%>
         <asp:BoundField DataField="DepartmentName"
            HeaderStyle-HorizontalAlign="Center" HeaderText="Department Name"
            ItemStyle-HorizontalAlign="Left">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Left" />
         </asp:BoundField>
         <asp:BoundField DataField="LocationName"
            HeaderStyle-HorizontalAlign="Center" HeaderText="Location"
            ItemStyle-HorizontalAlign="Left">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Left" />
         </asp:BoundField>
         <asp:BoundField DataField="SubLocation_Name"
            HeaderStyle-HorizontalAlign="Center" HeaderText="Sub Location"
            ItemStyle-HorizontalAlign="Left">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Left" />
         </asp:BoundField>
         <asp:BoundField DataField="EmpName"
            HeaderStyle-HorizontalAlign="Center" HeaderText="Hod Name"
            ItemStyle-HorizontalAlign="Left">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Left" />
         </asp:BoundField>
         <asp:BoundField DataField="EmpEmail"
            HeaderStyle-HorizontalAlign="Center" HeaderText="Email"
            ItemStyle-HorizontalAlign="Left">
            <HeaderStyle HorizontalAlign="Center" />
            <ItemStyle HorizontalAlign="Left" />
         </asp:BoundField>
         <asp:TemplateField HeaderStyle-BackColor="#666666" HeaderText="Hod Employee Code" ItemStyle-Width="5%">
            <HeaderStyle BackColor="#666666" />
            <ItemStyle HorizontalAlign="Center" />
            <ItemTemplate>
               <%--
                  <asp:TextBox ID="txtEmpCode" runat="server" Text='
                    <%#Eval("EmpCode")%>' />--%>
               <asp:TextBox ID="txtEmployeeSearch" onblur="checkItemSelected(this,isItemSelected3)" runat="server"
                  Text='<%#Eval("EmpCode")%>' CssClass="txtclass">
               </asp:TextBox>
               <br />
               <span >Text cannnot be left blank, Enter Employee code </span>
               <asp:TextBox ID="hdfDLSID" runat="server" Text='<%#Eval("DLSID")%>' Style="display: none">
               </asp:TextBox>
               <asp:AutoCompleteExtender ID="ExtEmployeeCode" runat="server" CompletionInterval="1" CompletionListCssClass="autoCompleteList"
                  CompletionListHighlightedItemCssClass="autoCompleteSelectedListItem" CompletionListItemCssClass="autoCompleteListItem"
                  CompletionSetCount="1" ContextKey='<%#Eval("DLSID")%>' EnableCaching="true" MinimumPrefixLength="3"
                  ServiceMethod="GetHodEmployeeList" ServicePath="~/UI/Requisition/Dropdown.asmx" TargetControlID="txtEmployeeSearch"
                  OnClientItemSelected="onItemSelected3" UseContextKey="true">
               </asp:AutoCompleteExtender>
               <%--  
                  <asp:Panel runat="server" ID="pnltxtEmployeeSearch" Height="200px" ScrollBars="Vertical"></asp:Panel>--%><%-- 
                  <asp:BalloonPopupExtender ID="BPEtxtEmployeeSearch" BalloonSize="Small" Position="TopRight"
                                                                                    CustomClassName="clsTxt" DisplayOnFocus="true" TargetControlID="txtEmployeeSearch" UseShadow="false"
                                                                                    BalloonStyle="Rectangle" BalloonPopupControlID="sptxtEmployeeSearch" runat="server"></asp:BalloonPopupExtender>--%><%--  
                  <span id="sptxtEmployeeSearch" runat="server" style="font-family: Century Gothic;">
                    <p>
                        <img alt="Info" src="../../Images/info.png" />&nbsp;&nbsp; Kindly select from the
                                                                list only
                                                                                    
                    </p>
                  </span>--%><%-- 
                  <asp:RequiredFieldValidator ID="rfvtxtEmployeeSearch" runat="server" ValidationGroup="Conf"
                                                                                    SetFocusOnError="true" ErrorMessage="
                    <img src='../../Images/alert.png' />  kindly provide details of Hod Employee Code"
                                                                                    CssClass="Alert" Display="Dynamic" ControlToValidate="txtEmployeeSearch">
                  </asp:RequiredFieldValidator>--%>
            </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField HeaderStyle-BackColor="#666666" HeaderText="Location HR Employee Code" ItemStyle-Width="4%">
            <HeaderStyle BackColor="#666666" />
            <ItemStyle HorizontalAlign="Center" />
            <ItemTemplate>
               <%--
                  <asp:TextBox ID="txtEmpCode" runat="server" Text='
                    <%#Eval("EmpCode")%>' />--%>
               <asp:TextBox ID="txtHrlocationEmployeeCode" onblur="checkItemSelected(this,isItemSelected4)" runat="server"
                  Text='<%#Eval("HrlocationEmployeeCode")%>' CssClass="txtclass">
               </asp:TextBox>
               <br />
               <span >Text cannnot be left blank, Enter Employee code </span>
               <asp:TextBox ID="hdfDLSID1" runat="server" Text='<%#Eval("DLSID")%>' Style="display: none">
               </asp:TextBox>
               <asp:AutoCompleteExtender ID="ExtHrlocationEmployeeCode" runat="server" CompletionInterval="1" CompletionListCssClass="autoCompleteList"
                  CompletionListHighlightedItemCssClass="autoCompleteSelectedListItem" CompletionListItemCssClass="autoCompleteListItem"
                  CompletionSetCount="1" ContextKey='<%#Eval("DLSID")%>' EnableCaching="true" MinimumPrefixLength="3"
                  ServiceMethod="GetHREmployeeList" ServicePath="~/UI/Requisition/Dropdown.asmx" TargetControlID="txtHrlocationEmployeeCode"
                  OnClientItemSelected="onItemSelected4" UseContextKey="true">
               </asp:AutoCompleteExtender>
               <%--  
                  <asp:Panel runat="server" ID="pnltxtEmployeeSearch" Height="200px" ScrollBars="Vertical"></asp:Panel>--%><%--  
                  <asp:BalloonPopupExtender ID="BPEtxtHrlocationEmployeeCode" BalloonSize="Small" Position="TopRight"
                                                                                   CustomClassName="clsTxt" DisplayOnFocus="true" TargetControlID="txtHrlocationEmployeeCode" UseShadow="false"
                                                                                   BalloonStyle="Rectangle" BalloonPopupControlID="sptxtHrlocationEmployeeCode" runat="server"></asp:BalloonPopupExtender>--%><%--  
                  <span id="sptxtHrlocationEmployeeCode" runat="server" style="font-family: Century Gothic;">
                    <p>
                        <img alt="Info" src="../../Images/info.png" />&nbsp;&nbsp; Kindly select Reporting
                                                               Manager from the list only
                                                                                   
                    </p>
                  </span>--%><%--  
                  <asp:RequiredFieldValidator ID="rfvtxtHrlocationEmployeeCode" runat="server" ValidationGroup="Conf"
                                                                                   SetFocusOnError="true" ErrorMessage="
                    <img src='../../Images/alert.png' />  kindly provide details of Location HR Employee Code"
                                                                                   CssClass="Alert" Display="Dynamic" ControlToValidate="txtHrlocationEmployeeCode">
                  </asp:RequiredFieldValidator>--%>
            </ItemTemplate>
         </asp:TemplateField>
         <%--   
            <asp:TemplateField HeaderText="Emp Code" ItemStyle-Width="4%">
                <ItemTemplate>
                    <asp:TextBox ID="txtEmpCode" runat="server" Text='
                        <%#Eval("EmpCode")%>' />
                        <asp:RequiredFieldValidator ID="rfvEmpCode" ControlToValidate="txtEmpCode" runat="server"
                                                                   ErrorMessage="Required" ForeColor="Red" InitialValue="0" ValidationGroup='<%# "ValidationGroup_"   Container.DataItemIndex %>'>
                        </asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>--%>
      </Columns>
   </asp:GridView>
</div>

I want to required field validator for each text box having blank spaces using javascript in asp.net C#.

how to validate grid view textbox using javascript.

I need to validate textbox in grid view using javascript in each row row of grid view.

CodePudding user response:

Instead of adding multiple required field validators, I would use Group Validation or use the power of jquery to validate based on the classes.

To validate using javascript you can add a class to your html elements and then listen to your click event or blur event.

For example, if I have a thousand textboxes that I need to validate on a single button click:

<asp:TextBox runat="server" ID="tb1"></asp:TextBox>
.
.
.
<asp:TextBox runat="server" ID="tb1000"></asp:TextBox>

What I would do is, add .required class on each element that I need to validate (for multiple rows in gridview, ASP.NET would add that class if you add it on your template).

So, after updating, my textbox should look like this:

<asp:TextBox runat="server" CssClass="required" ID="tb1"></asp:TextBox>
.
.
.
<asp:TextBox runat="server" CssClass="required" ID="tb1"></asp:TextBox>

Since, all the required fields have a class (required) on them, before clicking the submit button, I can validate if any of the field was left blank:

$('#btnSubmitData').on('click', function(){
   var requiredFields = $('.required'); // will give you all the elements that have a .required class
   for(var i = 0; i < requiredFields.length; i  ){
      if ($(requiredFields[i]).val().trim() == '') { // trim() to remove blank spaces
         return false; // returning false would prevent the server side event from triggering.
      }
   }
});

You can also highlight the textbox that was left blank by modifying its css properties:

$('#btnSubmitData').on('click', function(){
   var requiredFields = $('.required'); // will give you all the elements that have a .required class
   for(var i = 0; i < requiredFields.length; i  ){
      if ($(requiredFields[i]).val().trim() == '') { // trim() to remove blank spaces
         $(requiredFields[i]).addClass('bg-red');
         return false; // returning false would prevent the server side event from triggering.
      }
   }
});

CodePudding user response:

function Validate() {
    //Reference the GridView.
    var grid = document.getElementById("<%=gView.ClientID %>");

    //Reference all INPUT elements.
    var inputs = grid.getElementsByTagName("TextBox");

    //Set the Validation Flag to True.
    var isValid = true;
    for (var i = 0; i < inputs.length; i  ) {
        //If TextBox.
        if (inputs[i].type == "text") {
           
            //If Blank
            if (inputs[i].value == "") {
                isValid = false;
            } else {
                isValid = true;
            }
        }
    }

    return isValid;
}
  • Related