ASP.Net Form Validation Using JavaScript

In this article we will learn how to validate ASP.Net form controls using JavaScript.


When you create an ASP.Net form then before submitting the form data on the server its necessary to ensure that the user has providedvalid data to avoid any erroneous data to be inserted into the database. Their are many ways to validate ASP.Net form data, we will learn one by one. In this article we will learn about client-side validation that is done using JavaScript.
So let us learn some basics because I have written this article only focusing on beginners and students.

What Form Validation is

Ensuring that data entered by the user into the form is proper and valid as per our business requirements is called as Form Validation.

Types of validation 
  • Client Side Validation
  • Server Side Validation

Client side validation

Validation done in the browser before sending the form data to the server using JavaScript, jQuery and VBScript is called client-side validation.

Server Side Validation

Validation done at the server level after sending the form data to the server but before entering the data into the database is called server-side validation.

Where to write JavaScript code in ASP.Net Form?

You can write the JavaScript code in the ASP.Net Page in the following sections. 
  • Head Section

    You can write the JavaScript code in the head section, it is the recommended way to write the code, the code must be enclosed in the following syntax:
    1. <head id="Head1" runat="server">  
    2. <script type="text/javascript">  
    3.     //write JavaScript code here  
    4. </script>  
    5. </head>  
  • Body Section

    You can also write the JavaScript at the body section of the page, the function written inside the body tag will automatically be called after page load.
  • External file

    You can write the code by adding the JavaScript file template that is provided by the .Net framework and after that we can add the reference of the .js file in the head section or body section.

Creating JavaScript function

The function is created in JavaScript using the function keyword followed by name.

  1. function VildateData()  
  2. {  
  3.    //write code here  
  4. }  
In the preceding syntax function is the keyword provided by the JavaScript to declare a function and the VildateData() is the function name, now write the code inside the function as in the following.


  1. function VildateData()  
  2. {  
  3.     alert("this is the JavaScript");  
  4. }  
I hope you now understand the basics of validation in JavaScript, now let us create the one sample web application that demonstrates how to do validation.

Let us first create the web application with two web pagesas in the following:

  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010"
  2. "File" - "New Website" - "C# - Empty website" (to avoid adding a master page)
  3. Give the web site a name, such as Validation or whatever you wish and specify the location
  4. Then right-click on the solution in the Solution Explorer then select "Add New Item" - "Default.aspx page" (add two pages).

We are adding two web pages because our requirement is, in the first web page there is form data to be filled in by the user and only after validating the form data, the form will be redirected to the next page.

The first page source code <body> tag will lookas in the following:

  1. <body bgcolor="#3366ff">  
  2.     <form id="form2" runat="server">  
  3.     <br />  
  4.     <br />  
  5.     <div>  
  6.         <table>  
  7.             <tr>  
  8.                 <td>  
  9.                     Name  
  10.                 </td>  
  11.                 <td>  
  12.                     <asp:TextBoxID="txtUserId" runat="server"></asp:TextBox>  
  13.                 </td>  
  14.             </tr>  
  15.             <tr>  
  16.                 <td>  
  17.                     Email Id  
  18.                 </td>  
  19.                 <td>  
  20.                     <asp:TextBox ID="txtmail" runat="server"></asp:TextBox>  
  21.                 </td>  
  22.             </tr>  
  23.             <tr>  
  24.                 <td>  
  25.                     Gender  
  26.                 </td>  
  27.                 <td>  
  28.                     <asp:DropDownList ID="ddlType" runat="server">  
  29.                         <asp:ListItem Value="0">-Select-</asp:ListItem>  
  30.                         <asp:ListItem Value="1">Male</asp:ListItem>  
  31.                         <asp:ListItem Value="2">Female</asp:ListItem>  
  32.                     </asp:DropDownList>  
  33.                 </td>  
  34.             </tr>  
  35.             <tr>  
  36.                 <td>  
  37.                     word  
  38.                 </td>  
  39.                 <td>  
  40.                     <asp:TextBox ID="txt1" runat="server" TextMode="word"></asp:TextBox>  
  41.                 </td>  
  42.             </tr>  
  43.             <tr>  
  44.                 <td>  
  45.                     Confirm word  
  46.                 </td>  
  47.                 <td>  
  48.                     <asp:TextBox ID="txt2" runat="server" TextMode="word"></asp:TextBox>  
  49.                 </td>  
  50.             </tr>  
  51.             <tr>  
  52.                 <td>  
  53.                 </td>  
  54.                 <td>  
  55.                     <asp:Button ID="btnSave" runat="server" Text="Create" OnClientClick="return userValid();" />  
  56.                     <asp:Button ID="Button1" runat="server" Text="Reset" />  
  57.                 </td>  
  58.             </tr>  
  59.         </table>  
  60.         <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  
  61.     </div>  
  62.     </form>  
  63. </body>  
Look at the preceding source code closely; see the id's of controls that play the important role in JavaScript validation by reading the ASP.Net control values in JavaScript code.

The design view of the preceding source code will look as in the following:


I hope you have created the same form as above for demonstration purposes.

Methods to read ASP.Net controls values in JavaScript are as:

There are three main methods shown in the above image in the red square to read the ASP.Net controls values; they are:

getElementById: this method is used to read the controls values by their ID.
getElementByName: this method is used to read the controls values by their Name.
getElementByTagName: this method is used to read the controls values by their TagName.

In this article we use the getElementById method to read the control's values and external .js file to write JavaScript code, so let us see step-by-step how to add the JavaScript file.
  1. Right-click on Solution Explorer then select "Add New Item" then the in the script.js page rename the .js page as you wish, I have renamed it to UserValidation.js
  2. Create the function inside the UserValidation.js file named userValid() as:
  1. function userValid()  
  2. {  
  3.     //write code here  
  4. }  
Now declare the variable inside the function using the var keyword to read the ASP.Net control values by their ids and assign the values to the declared variable..
  1. function userValid()   
  2. {  
  3.     var Name, , gender, con, EmailId, emailExp;  
  4.     Name = document.getElementById("txtUserId").value;  
  5.     gender = document.getElementById("ddlType").value;= document.getElementById("txt1").value;  
  6.     con = document.getElementById("txt2").value;  
  7.     EmailId = document.getElementById("txtmail").value;  
  8.     emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([com\co\.\in])+$/; // to validate email id  
  9. }  
In the code above I have taken the ASP.Net control's values in variables so it cannot be repeated again and again in our function the emailExp variable holds the pattern of the email id in the form of a regular expression.

Now add the condition to ensure that all controls have a value, if the values are not entered in the form control then it will show a message. The condition will be as follows:

  1. if (Name == '' && gender == 0 && == '' && con == '' && EmailId == '')  
  2. {  
  3.     alert( "Enter All Fields");  
  4.     return false;  
  5. }  
In the preceding condition, to ensure that the form control's values are blank the message Enter All Fields  is shown to the user and finally we are returning false; that is very important.

Importantance of returning false

It's very important to use the return false statement after the condition block that return false so if validation determines that the business requirements are not met then the form cannot be submitted. If you do not return false then the message will be displayed to the user that all fields are required but the form will be post back and it gives you the second page directly. Therefore the return false statement works similar to the Required Field validator of ASP.Net.

I hope you understand the concept.

The condition that checks both text boxes for word are as in the following:
  1. if ( != con)  
  2. {  
  3.     alert( "word not match");  
  4.     return false;  
  5. }  
In the preceding condition, we are checking that the two texboxes have words, in other words the word and confirm word.

Condition to determine if the email address is valid:

  1. if (EmailId != '')  
  2. {  
  3.     if (!EmailId.match(emailExp))  
  4.     {  
  5.         alert( "Invalid Email Id");  
  6.         return false;  
  7.     }  
  8. }  
In the preceding condition, first we ensure that the email id is not blank then we match the email id entered into the text box to the Regular Expression that is saved in the emailExp variable.

The entire function will be as follows:

  1. function userValid() {  
  2. var Name, , gender, con, EmailId, emailExp;  
  3. Name = document.getElementById("txtUserId").value;  
  4. gender = document.getElementById("ddlType").value;= document.getElementById("txt1").value;  
  5. con = document.getElementById("txt2").value;  
  6. EmailId = document.getElementById("txtmail").value;  
  7. emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([com\co\.\in])+$/; // to validate email id  
  8. if (Name == '' && gender == 0 && == '' && con == '' && EmailId == '') {  
  9.     alert("Enter All Fields");  
  10.     return false;  
  11. }  
  12. if (Name == '') {  
  13.     alert("Please Enter Login ID");  
  14.     return false;  
  15. }  
  16. if (gender == 0) {  
  17.    alert("Please Select gender");  
  18.    return false;  
  19. }  
  20. if ( == '')  
  21. {  
  22.      alert("Please Enter word");  
  23.      return false;  
  24. }  
  25. if ( != '' && con == '')  
  26. {  
  27.     alert("Please Confirm word");  
  28.     return false;  
  29. }  
  30. if ( != con)  
  31. {  
  32.     alert("word not match");  
  33.     return false;  
  34. }  
  35. if (EmailId == '')  
  36. {  
  37.     alert("Email Id Is Required");  
  38.     return false;  
  39. }  
  40. if (EmailId != '')  
  41. {  
  42.     if (!EmailId.match(emailExp)  
  43.     {  
  44.         alert("Invalid Email Id");  
  45.         return false;  
  46.      }  
  47.   }  
  48.   return true;  
  49. } 
Adding the reference of external JavaScript file into the Head section of ASP.Net form

Just drag the .js file from the Solution Explorer to the Head section of the ASP.Net form that automatically adds the file reference path, it will look like as in the following:

  1. <head id="Head1" runat="server">  
  2. <script src="UserValidation.js" type="text/javascript">  
  3. </script>  
  4. </head >  
Calling JavaScript function on ASP.Net Button

To call the JavaScript function on the ASP.Net button we need to call the function in the ASP.Net button's OnClientClick property.


  1. <asp:Button ID="btnSave" runat="server" Text="Create" OnClientClick="return userValid();"/>  
I hope you have understood it then the Solution Explorer will look like as in the following:

In the preceding Solution Explorer, their are two ASP.Net pages, UserCreation.aspx and UserLanding.aspx along with the UserValidation.js JavaScript file. In the UserCreation.aspx page the user enters the form details and then only after validating the details the page is redirected to the UserLanding.aspx page.

Use the following code in the create button:
  1. protected void btn_Click(object sender, EventArgs e)  
  2. {  
  3.     Response.Redirect("UserLanding.aspx");  
  4. }  
In the code above, only after validating the form data, the page is redirected to the UserLanding.aspx page.

Now run the ASP.Net web application and click on the Create button without inserting any data in the form, then it will show the following alert message.


In the preceding screen you clearly see that even I have wriiten the code on the create button to redirect to the next page but it will not be redirected because the form data is blank and it does not satisfy our validation condition that we set.
In other words, it's clear that the validation is done at the client side in the browser level and only validates the data; it will execute the server-side code.

Now enter the invalid Email Id, it will show the following message:


Now enter the valid details.


Now click on the "Create" button; it will redirect to the next page as in the following:



For detailed code please download the zip file attached above.


From all the examples above we see how to validate the form data using JavaScript. I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.