Javascript Validation

Ssnkumar3
Posted by in JavaScript category on for Beginner level | Points: 250 | Views : 13373 red flag

In this tutorial we will see how to do client side validation using Javascript.

Introduction


This tutorial we will do client side validation using JavaScript. In my next article we will do the same validation using jQuery.

Objective


It is very easy for us to validate the Page using server side code or Asp.net Validation control. But doing validation using JavaScript gives us some nice experience. We will see how to do the validation by using JavaScript from scratch. For this tutorial we will use Visual Studio Ultimate and Asp.net Web application. However we can validate normal Html page using notepad editor also.


Create Project


Open visual studio then go to File Menu and Select New Website. In New Web Site select Visual C# under Templates Pane. In the list of project templates select Asp.Net Empty Web site. You can select other template also. Store the website in your preferred location. Once if it is done click OK.  Website created and stored in the mentioned location.

View the solution explorer. If it is not already opened Go to View and select the Solution explorer. We selected Empty Web site so the website added only web.config file. Now right click the solution explorer and select add new Item. In the window Select WebForm then give appropriate Name and click Add. Now WebForm added into our solution 



Design


Next couple of TextBoxes are added, DropDownList and one Button to design the page looks like below.


Source code for the above design.

<table>
            <tr>
                <td><span id="spName">Enter Name</span></td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td><span id="spDesig">Select Designation</span></td>
                <td>
                    <asp:DropDownList ID="ddlDesig" runat="server">
			<asp:ListItem Value="-1">Select</asp:ListItem>
                        <asp:ListItem Value="1">Trainee</asp:ListItem>
                        <asp:ListItem Value="2">Programmer</asp:ListItem>
                        <asp:ListItem Value="2">Senior Programmer</asp:ListItem>
                        <asp:ListItem Value="4">Team Leader</asp:ListItem>
                        <asp:ListItem Value="5">Project Manager</asp:ListItem>
                    </asp:DropDownList></td>
            </tr>
            <tr>
                <td><span id="spSalary">Enter Salary</span></td>
                <td><asp:TextBox ID="txtSal" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSubmit" OnClientClick="javascript:return fnValidate();" Text="Submit" runat="server" />
                </td>
            </tr>
        </table>

Adding Script Reference


After we designed the page we need to validate the Page whenever user hit the submit button. So we need to add JavaScript file to validate the Page. Open solution explorer then Right click the Website and add New item. Select JavaScript file and name the file as validate.js.



Next we need to refer the script file in our Page. In our aspx page we need to refer the script file in Head section.

<script src="validate.js"></script> 

Validation Part


Now we are ready to validate the Page. Open validate.js file. Create a function called fnValidate. Below snippet shows how to create function in JavaScript.
function fnValidate()
{

}
Once function is created in script file add following code inside the function to validate the TextBox (txtName). 

Note: JavaScript is case sensitive. It uses camel notation.
 if(document.getElementById('txtName').value=='')
{
	alert('Enter Name');
}
In the above code document.getElementById('txtName') gets the TextBox object and .value gets the value of the object. 'If' condition checks whether the TextBox have value or not. If it does not have value then its trigger alert message. 

Validating remaining element also be similar to above one. Triggering alert for every validation error will irritating the end user. So I modified the validation code little bit and final code seems like below.
function fnValidate() {
    var errorMessage = '';
    if (document.getElementById('txtName').value == '') {
        errorMessage += document.getElementById('spName').innerText + '\n';
    }
    if (document.getElementById('ddlDesig').value == '-1') {
        errorMessage += document.getElementById('spDesig').innerText + '\n';
    }
    if (document.getElementById('txtSal').value == '') {
        errorMessage += document.getElementById('spSalary').innerText + '\n';
    }
    if (isNaN(document.getElementById('txtSal').value)) {
        errorMessage += 'Enter Numeric Values only' + '\n';
    }
    if (errorMessage != '') {
        alert(errorMessage);
        return false;
    }
}
In the above code declared one variable called errorMessage. Also, instead of hard coding the error message value we get the label text. For getting the span value we use innerText (document.getElementById('spName').innerText) instead of value. For validating the numeric value (for salary) I used isNaN function. It will check whether the TextBox (txtSalary) have any non numeric value. Finally I throw the error message if the errorMessage variable is not empty.

Conclusion


Hope this article gives you some basic idea about how to validate a page using client side JavaScript. In feature article we will see some advanced JavaScript concept. Also we will see how to do the same validation using jQuery. Thanks for reading this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Ssnkumar3
Full Name: Sankara Narayanan
Member Level: Starter
Member Status: Member
Member Since: 2/17/2014 2:33:25 AM
Country: India



Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)