ASP.NET Form Validation 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 provided valid 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:
     
    <head id="Head1" runat="server">
    <script type="text/javascript">
        //write JavaScript code here
    </script>
    </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 the function

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

Syntax
function VildateData()
{
   //write code here
}

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.

Example
function VildateData()
{
    alert("this is the JavaScript");
}

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 pages as 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 look as in the following:

        <body bgcolor="#3366ff">
            <form id="form2" runat="server">
            <br />
            <br />
            <div>
                <table>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            <asp:TextBox ID="txtUserId" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Email Id
                        </td>
                        <td>
                            <asp:TextBox ID="txtmail" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Gender
                        </td>
                        <td>
                            <asp:DropDownList ID="ddlType" runat="server">
                                <asp:ListItem Value="0">-Select-</asp:ListItem>
                                <asp:ListItem Value="1">Male</asp:ListItem>
                                <asp:ListItem Value="2">Female</asp:ListItem>
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Password
                        </td>
                        <td>
                            <asp:TextBox ID="txtPass1" runat="server" TextMode="Password"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Confirm Password
                        </td>
                        <td>
                            <asp:TextBox ID="txtPass2" runat="server" TextMode="Password"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            <asp:Button ID="btnSave" runat="server" Text="Create" OnClientClick="return userValid();" />
                            <asp:Button ID="Button1" runat="server" Text="Reset" />
                        </td>
                    </tr>
                </table>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </div>
            </form>
        </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:

Design.png

I hope you have created the same form as above for demonstration purposes. Methods to read ASP.NET controls values in JavaScript are as:
javascriptmethod.png

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.
  • 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
  • Create the function inside the UserValidation.js file named userValid() as:
    function userValid()
    {
        //write code here
    }

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.

function userValid()
{
var Name, pass, gender, conpass, EmailId, emailExp;
Name = document.getElementById("txtUserId").value;
gender = document.getElementById("ddlType").value;
pass = document.getElementById("txtPass1").value;
conpass = document.getElementById("txtPass2").value;
EmailId = document.getElementById("txtmail").value;
emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([com\co\.\in])+$/; // to validate email id
}

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:

if (Name == '' && gender == 0 && pass == '' && conpass == '' && EmailId == '')
{
alert( "Enter All Fields");
return false;
}

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.

Importance 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 password are as in the following:

if (pass != conpass)
{
alert( "Password not match");
return false;
}

In the preceding condition, we are checking that the two texboxes have passwords, in other words the password and confirm password.

Condition to determine if the email address is valid:
if (EmailId != '')
{
if (!EmailId.match(emailExp))
{
alert( "Invalid Email Id");
return false;
}
}

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:

function userValid() {
var Name, pass, gender, conpass, EmailId, emailExp;

Name = document.getElementById("txtUserId").value;
gender = document.getElementById("ddlType").value;
pass = document.getElementById("txtPass1").value;
conpass = document.getElementById("txtPass2").value;
EmailId = document.getElementById("txtmail").value;
emailExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([com\co\.\in])+$/; // to validate email id

if (Name == '' && gender == 0 && pass == '' && conpass == '' && EmailId == '') {
    alert("Enter All Fields");
    return false;
}
if (Name == '') {
    alert("Please Enter Login ID");
    return false;
}
if (gender == 0) {
   alert("Please Select gender");
   return false;
}
if (pass == '')
{
     alert("Please Enter Password");
     return false;
}
if (pass != '' && conpass == '')
{
    alert("Please Confirm Password");
    return false;
}
if (pass != conpass)
{
    alert("Password not match");
    return false;
}
if (EmailId == '')
{
    alert("Email Id Is Required");
    return false;
}
if (EmailId != '')
{
    if (!EmailId.match(emailExp)
    {
        alert("Invalid Email Id");
        return false;
     }
  }
  return true;
}
  • 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:

<head id="Head1" runat="server">
<script src="UserValidation.js" type="text/javascript">
</script>
</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.

Example
<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:

solutionexplorer.png


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:
protected void btn_Click(object sender, EventArgs e)
{
    Response.Redirect("UserLanding.aspx");
}

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.

blank.png

In the preceding screen you clearly see that even I have written 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:

invalidemailid.png

Now enter the password that does not match the confirm password, it will show the following message:

passntmatch.png

Now enter the valid details.

validdetails.png

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

final.png

Summary

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.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode