Text Box Validation In ASP.NET Using JavaScript

Today we are going to learn how to validate the Text Box using the java script in asp.net.

First create the Text box and one button in your aspx file as I have written the code to create the text box and button below.

ASP.Net Code

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.     <div>  
  4.       
  5.         <table class="style1">  
  6.             <tr>  
  7.                 <td>  
  8.                     <asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label>  
  9.                          
  10.                     <asp:TextBox ID="txtUName" runat="server"></asp:TextBox>  
  11.                 </td>  
  12.             </tr>  
  13.             <tr>  
  14.                 <td>  
  15.                     <asp:Label ID="Label2" runat="server" Text="Password"></asp:Label>  
  16.                            
  17.                     <asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>  
  18.                 </td>  
  19.             </tr>  
  20.             <tr>  
  21.                 <td>  
  22.                                 
  23.                     <asp:Button ID="btnLogin" runat="server" Text="Login" Width="120px" 
  24.                         OnClientClick="return userValid();" />  
  25.                      </td>  
  26.             </tr>  
  27.         </table>  
  28.       
  29.     </div>  
  30.     </form>  
  31. </body>   
To validate the User Name and Password field Using java Script. Write a java script in Head tag as show below...
 
Java Script Code
 
  1. <script type="text/javascript">    
  2.     
  3.         function userValid() {    
  4.            var UName= document.getElementById("txtUName").value;    
  5.            var Pwd= document.getElementById("txtPwd").value;    
  6.     
  7.            if (UName == '')    
  8.            {    
  9.             alert("Please enter User Name");    
  10.             return false;    
  11.            }    
  12.     
  13.            if (Pwd == '')    
  14.            {    
  15.            alert("Please enter Password");    
  16.            return false;    
  17.            }    
  18.         }    
  19.      </script>     
 
If you like the above blog please do like and comment... :)