jQuery Validation

Ssnkumar3
Posted by in jQuery category on for Beginner level | Points: 250 | Views : 12990 red flag
Rating: 5 out of 5  
 1 vote(s)

This article we will see how to do the simple validation using jQuery.
Recommendation
Read Javascript Validation before this article.

Introduction


In my previous article we saw how to do the client side validation using JavaScript. Please read the article from here. In this article we will see how to do the same validation using jQuery. 

Create New Website


For this tutorial we are going to use the same solution what we have used for the previous tutorial. Instead of using the same website we are going to add new website from the existing solution. Open Solution Explorer and right click the solution to add new website. In the available template section, select ASP.NET Web Forms Website. Don't forget to mention the location where you want to save the website. After clicking OK visual studio added new website to the existing solution. 



When we expand the solution explorer lot of files are added in the website. Visual studio added images, scripts, CSS, themes, etc in the website. 



Design


Instead of doing the validation with existing aspx file we will add new Web Form and name it as JsVal.aspx.



Next I opened the aspx page and adding some controls to design the page looks like below.



Code for the above design.
<table class="auto-style1">
            <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" Text="Submit" runat="server" />
                </td>
            </tr>
        </table>

Adding script file


Now we need to add script file to write our validation code. Right click the script folder, click add new item then select JavaScript file from the available template and name it as jsValidation.



Script Reference

After that we need to reference both jQuery and jsValidation file in our Page. Visual studio already added jQuery files in the script folder. So now we need to refer those files in our Page. If we expand the script folder there are several jQuery script files are available. For this article we are going to refer only jQuery. If we are going to use the jQuery in production environment than refer min version (jQuery-1.7.1.min) of jQuery. Add below code in Head section of aspx page to refer script files.

<script src="Scripts/jquery-1.7.1.js"></script>
<script src="Scripts/jsValidation.js"></script>

Validation Part


Open jsValidation file. Add the following code to validate the Name (txtName) TextBox.
$(document).ready(function () {
    $('#btnSubmit').click(function () {
        if ($('#txtName').val()== '') {
            alert('Enter Name');
        }
    })
})
In the above code $(document).ready ensure that the page is completely loaded. Unlike JavaScript, jQuery provide several options to select the Html object. Here $('#btnSubmit') select the submit button object then it added the click event. Within the click event we added our validation logic. Similarly we can select the TextBox object by using $('#txtName'). $('#txtName').val() retrieve the value of the TextBox object. If the value of $('#txtName').val() is empty then we trigger the alert message to the end user.

Note: There are several jQuery selectors are available to select Html Element. For this article we are using the Id to select Html element. So we used # symbol. For detailed jQuery object selector please refer jQuery documentation.

Also we modified the code to validate the remaining element. Final code seems below.
$(document).ready(function () {
    $('#btnSubmit').click(function () {
        var errorMessage = '';
        if ($('#txtName').val()== '') {
            errorMessage += $('#spName').text() + '\n';
        }
        if ($('#ddlDesig').val() == '-1') {
            errorMessage += $('#spDesig').text() + '\n';
        }
        if ($('#txtSal').val() == '') {
            errorMessage += $('#spSalary').text() + '\n';
        }
        if (isNaN($('#txtSal').val())) {
            errorMessage += 'Enter Numeric Values only' + '\n';
        }
        if (errorMessage != '') {
            alert(errorMessage);
            return false;
        }
    })
})
In the above code we added errorMessage variable to store the error values. Instead of hard coding the error values we retrieve the label value of corresponding element by using jQuery. For retrieving span value we used $('#spName').text() method instead of val() which we used for TextBox. Finally if the errorMessage variable have values then we show the error message to the end user.

Conclusion


In this article we used jQuery to validate the Page. Hope this article helps understand how to do the validation using jQuery. In future articles, we will see how to pass data from client to server 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)