Tuesday, August 24, 2010

JavaScript form Validation in asp.net

 JavaScript form Validation in asp.net  
 This simple code show how to do simple client side validation using javascript  
   
 Create a form with following:  
   
 1. Emp Name : <asp:TextBox ID="txtEmpName" />  
 2. Email : <asp:TextBox ID="txtEmailAdd" />  
 3. URL : <asp:TextBox ID="txturl" />  
 4. Zip : <asp:TextBox ID="txtZip" />  
   
 <asp:Button ID="btnAdd" OnClientClick=" return form_validate()" runat="server" Text="Submit" />  
   
 Write this javascript to your aspx page  
   
 <script language="javascript" type="text/javascript">  
 function form_validate()  
 {  
      if (document.getElementById("<%=txtEmpName.ClientID%>").value=="")  
      {  
           alert("Please enter the name");  
           document.getElementById("<%=txtEmpName.ClientID%>").focus();  
           return false;  
      }  
      if(document.getElementById("<txtEmailAdd.ClientID %>").value=="")  
      {  
           alert("Email id can not be blank");  
           document.getElementById("<%=txtEmailAdd.ClientID %>").focus();  
           return false;  
      }  
      var mailPattern = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;  
      var mailid=document.getElementById("<%=txtEmailAdd.ClientID %>").value;  
      var matchArr = mailid.match(mailPattern);  
      if (matchArr == null)  
      {  
           alert("Your email is incorrect.");  
           document.getElementById("<%=txtEmailAdd.ClientID %>").focus();  
           return false;  
      }  
      if(document.getElementById("<%=txturl.ClientID %>").value=="")  
      {  
           alert("Please enter URL");  
           document.getElementById("<%=txturl.ClientID %>").value="http://"  
           document.getElementById("<%=txturl.ClientID %>").focus();  
           return false;  
      }  
      var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"  
      var tempURL=document.getElementById("<%=txturl.ClientID%>").value;  
      var matchURL=tempURL.match(Url);  
      if(matchURL==null)  
      {  
           alert("URL incorrect try again||");  
           document.getElementById("<%=txturl.ClientID %>").focus();  
           return false;  
      }  
      if (document.getElementById("<%=txtZIP.ClientID%>").value=="")  
      {  
           alert("Zip Code not correct");  
           document.getElementById("<%=txtZIP.ClientID%>").focus();  
           return false;  
      }  
      var digits="0123456789";  
      var temp;  
      for (var i=0;i {  
      temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);  
      if (digits.indexOf(temp)==-1)  
      {  
           alert("Please enter correct zip code");  
           document.getElementById("<%=txtZIP.ClientID%>").focus();  
           return false;  
      }  
 }  
 return true;  
 }  
 </script>  
   
 Thanks & Regards  
 Santosh  

7 comments: