Validation summary in JavaScript
This blog details how to use the validation summary.
Here there are four text box controls. Assume all the fields are mandatory and it will show the validation summary.
Design:
- <table cellpadding="0" cellspacing="0" border="0" width="100%">
- <tr>
- <td>
- Name:
- </td>
- <td>
- <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- Address:
- </td>
- <td>
- <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- City:
- </td>
- <td>
- <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- State:
- </td>
- <td>
- <asp:TextBox ID="txtState" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- <asp:Button ID="btnSubmit" runat="server" OnClientClick="return ValidateControls();" Text="Submit" />
- </td>
- <td>
- <asp:Button ID="btnReset" runat="server" Text="Reset" />
- </td>
- </tr>
- </table>
Java Script:
- <script type="text/javascript">
- function ValidateControls()
- {
- var txt = "Required to fill the following field(s)";
- var opt = 0;
-
- if (document.getElementById('<%=txtName.ClientID %>'))
- {
- if (document.getElementById('<%=txtName.ClientID %>').value == "")
- {
- txt += "\n - Name";
- var opt = 1;
- }
- }
-
- if (document.getElementById('<%=txtAddress.ClientID %>'))
- {
- if (document.getElementById('<%=txtAddress.ClientID %>').value == "")
- {
- txt += "\n - Address";
- var opt = 1;
- }
- }
-
- if (document.getElementById('<%=txtCity.ClientID %>'))
- {
- if (document.getElementById('<%=txtCity.ClientID %>').value == "")
- {
- txt += "\n - City";
- var opt = 1;
- }
- }
-
- if (document.getElementById('<%=txtState.ClientID %>'))
- {
- if (document.getElementById('<%=txtState.ClientID %>').value == "")
- {
- txt += "\n - State";
- var opt = 1;
- }
- }
-
- if (opt == "1")
- {
- alert(txt);
- return false;
- }
-
- return true;
- }
- </script>