Last updated: 7th June 2024
Validations are important when you create forms that require your users to enter valid and complete data. You can have a GridView control in your form to do multiple entries. When you use a GridView control to add or edit records, you will need controls like a textbox, dropdown list etc. Therefore, you will require few client side scripts that would validate these entries before submission. I’ll show how using few lines of JavaScript code you can validate textbox and dropdownlist in a GridView control.The example here is this article is slightly different, as I’ll bind the GridView control to a database table using SqlDataSource. There are few myths about SqlDataSource and there are talks about its limitations. However, it's a very useful and flexible control. You can easily bind it with a database table and later bind it to a GridView control.
Let’s assume, I just want to edit the data and wish to do it explicitly, that is, without the auto generated buttons. Therefore, I’ll set the defaults as false and add couple of link buttons to do the editing. This way I can handle it better and calling the JavaScript function for validation would be easy.
<div style="width:500px;"> <asp:GridView ID="grd" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="EmpID" AutoGenerateEditButton="false" runat="server"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lnkEdit" Text="Edit" runat="server" CommandName="Edit" /> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="lnkUpdate" Text="Update" CommandName="Update" OnClientClick="return validate(this)" runat="server" /> <asp:LinkButton ID="lnkCancel" Text="Cancel" runat="server" /> </EditItemTemplate> </asp:TemplateField> <%--DATA BOUND COLUMNS--%> <asp:BoundField DataField="EmpID" HeaderText="ID" SortExpression="EmpID" ReadOnly="true" /> <asp:BoundField DataField="EmpName" HeaderText="Employee Name" SortExpression="EmpName" ReadOnly="true" /> <asp:BoundField DataField="Mobile" HeaderText="Mobile No." SortExpression="Mobile" /> <asp:BoundField DataField="Email" HeaderText="Email ID" SortExpression="Email" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DNAConnectionString %>" SelectCommand="SELECT [EmpID], [EmpName], [Mobile], [Email] FROM [EmployeeDetails]" UpdateCommand="UPDATE EmployeeDetails SET Mobile = @Mobile, Email = @Email WHERE EmpID = @EmpID"> <UpdateParameters> <asp:Parameter Name="Mobile" /> <asp:Parameter Name="Email" /> </UpdateParameters> </asp:SqlDataSource> </div>
I am using a dummy SQL Server table to fetch and populate data to the GridView. You can see the data bound fields with headers. I have set the AutoGenerateEditButton=false and to replace it I have added a link button inside the <ItemTemplate> tag, with the CommandName as Edit.
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
When you click the Edit link button it would display two more link buttons in edit mode to update data or to cancel the editing.
<EditItemTemplate> <asp:LinkButton ID="lnkUpdate" Text="Update" CommandName="Update" OnClientClick="return validate(this)" runat="server" /> <asp:LinkButton ID="lnkCancel" Text="Cancel" runat="server" /> </EditItemTemplate>
See the above markup, it has the OnClientClick event that would call a JavaScript function called validate(). This is where we write our script to find and validate entries.
<script> // JAVASCRIPT FOR VALIDATION. function validate(ctrl) { var grdRow = ctrl.parentNode.parentNode; var grdControl = grdRow.getElementsByTagName("input"); // LOOP THROUGH EACH INPUT CONTROL IN THE GRIDVIEW. for (var i = 0; i < grdControl.length; i++) { if (grdControl[i].type = 'text') { if (grdControl[i].value === "") { alert(grdControl[i].title + ' is required.'); return false; } } } } </script>
The function validate() takes a single parameter, which is a reference of the control that calls the function. See the markup, the calling control is a LinkButton. Using the reference, we will get its parent control and later we will get all the input type controls.
Remember, when you click the Edit link button, it would show two textboxes in edit mode. The remaining two (the first two) bound controls are read only.
Finally, we loop through each control, check the type of each control, and find only controls with type text. An input control can be a button, text etc. Once found, check if its not empty. See how I am using the value and title to the pinpoint the controls that might be empty.
if (grdControl[i].type = 'text') { if (grdControl[i].value === "") { alert(grdControl[i].title + ' is required.'); return false; } }
Add JavaScript Validation to a DropDownList Control
You can apply a similar principle to a DropDownList control that you have added in your GridView control. Yes, you can attach a DropDownList to the SqlDataSource control. Like this…
<asp:TemplateField HeaderText="Employee Name"> <EditItemTemplate> <asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1" DataTextField="EmpName" DataValueField="EmpName" AppendDataBoundItems="true"> <asp:ListItem>-- pick a name --</asp:ListItem> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField>
Once I have attached the dropdownlist to the data source control, I have added a default value --pick a name -- in the beginning of the list. The dropdown has a list of employee names.
The script will check if the user has selected a valid employee name from the list.
<script> // FOR DROPDOWNLIST. function validate(ctrl) { var grdRow = ctrl.parentNode.parentNode; var grdControl = grdRow.getElementsByTagName("select"); for (var i = 0; i < grdControl.length; i++) { if (grdControl[i].value == "-- pick a name --") { alert("Select a name from the list"); return false; } } } </script>
Unlike the previous script (above), here I’ll search for select type controls. Using the method getElementByTagName() I can filter out <select> tags (elements). Finally, I’ll check the value that the user has picked from the list. If its not a valid name, show a message.
Add multiple controls to the GridView control and check the script. Remember, client validations are not fool proof and you cannot rely on these scripts only. Always add server side scripts along with client scripts to prevent any breach while submitting form data.