Friday 26 October 2012

Client Side Validation using JavaScript

Introduction

In this article how we can validate TextBox and DropDownList using JavaScript.


OnClientClick="return validate();" is used to call the JavaScript function on click of the Submit button.
Now we will add JavaScript code to implement client side implementation.
Firstly we will add a JavaScript function:

<script type="text/javascript">
function form_validate()
{
//Java script
}
 </script>

When user enters wrong information or may the user leaves a textbox blank, then the client side validation will be work. This will reduce server traffic.
 the complete JavaScript function:


<script type="text/javascript">

         function form_validate() {
             if (document.getElementById("<%=Txt_userid.ClientID%>").value == "") {
                 alert("Please enter UserId");
                 document.getElementById("<%=Txt_userid.ClientID%>").focus();
                 return false;
             }
             if (document.getElementById("<%=Txt_password.ClientID %>").value == "") {
                 alert("please enter password");
                 document.getElementById("<%=Txt_password.ClientID %>").focus();
                 return false;
             }
               if (document.getElementById("<%=ddllist.ClientID %>").value =='Select') {
                 alert("please enter password");
                 document.getElementById("<%=ddllist.ClientID %>").focus();
                 return false;
             }
         }
  </script>

 </head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>

 <asp:TextBox ID="Txt_userid "  runat="server"></asp:TextBox>

<asp:TextBox ID="Txt_password "  runat="server"></asp:TextBox>

<asp:DropDownList  ID="ddllist" runat="server"></asp:DropDownList>

  <asp:Button ID="Btn_Submit"  runat="server"
             Text="Submit" onclick="Btn_Submit_Click" OnClientClick="return form_validate()" />     
    </form>
</body>
</html>


No comments:

Post a Comment