ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

JQuery Client-side Validation for Text inputs

Updated on May 23, 2016

Introduction

This article shows you how to validate input text on HTML forms using JQuery. Client-side validation is very important in form validation. Databases store user inputs collected in HTML forms. This process will sift the trash coming into databases. Many ready made plug-ins are freely available for the two types of validation which we know as client side and server side. The below mentioned HTML code is an example for validating the input ‘Name’.

Basic html layout

<form id="form1" action="" method="post" >
    <!--step three-->
    	<div>
        <span>First Name</span>
        <input id="txtname" type="text" /> <span id="infotext">*</span><br />
        <input id="Submit1" type="submit" value="submit" />
       
    </div>
</form> 

The code above will create a simple html form containing a text box, label and a button. Now let’s study this code in detail. To begin with, all the input controls are needed to place in the HTML form.

Once the action is submitted, the HTML form will carry out the action. Based on the setting, this can be either GET or POST. The placeholder of the HTML controls is the ‘div’ tag and it is encircled by the HTML input controls. This is essential; otherwise W3C validation errors occur without the placeholder. To collect information and display error messages to users, input text box and infortext span are available. Afterwards, the form action will be generated by the submit button when it is clicked.

The basic view of P1C1 can be shown as follows.

Jquery Validation Form
Jquery Validation Form

Jquery Reference settings

Now the form is prepared for client side validation. You need to download the JQuery library reference in order to carry on the JQuery validation (www.jquery.org). After you download the reference, set it as shown below.

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

In HTML coding it is better to place all your .JS files in a separate folder. Similarly, another JS file called valitioninput.js should be created and saved in the same file. This file should contain all the custom validation codes.

<script type="text/javascript" src="js/validationinput.js"></script>


Building the jquery validation code

You need to add page ready() event before you begin any JQuery coding. It should be placed as shown below.

$(document).ready(function() {
//All your code will wirte inside here.

});
After the page loads in the browser, the code snippets for events and others will be inside the above method and will start functioning. In Javascript coding also we need to declare variables to read and store input values same as in other programming languages.

Read required inputs

The selectors that are going to be used should be identified so as to read values from HTML Form controls. Choosing a selector is helpful to read, assign or trigger events of HTML controls. CSS class, control ID and the control TAG name are the three types of selectors to read HTML controls. Here to select each element, I’ve used pseudo ID. Next we need to decide the required values. In this situation we’re going to validate only one text box. Therefore the text box value and its span tag to display the error message should be coded.

var name = $("#txtname"); //textbox you are going to validate
var nameInfo = $("#infotext"); //to display error message

These are the first two lines of code which are inside the Document Ready Event. These two variables act globally for all other functions within the ready event.

Events to be validated

Now let’s think about the events needed to validate this name text box. At this time you know that the submit event of the Form should be handled. Why? We have to perform validation for input controls before it is submitted. For navigation through text input fields sometimes users may use either TAB or arrow keys. In such a situation the system should validate the input at that moment. Here, the input control should be handled onBlur event. If the user selects the mouse instead of the TAB or arrow keys, onKeyDown event should be handled.

Submit event

The below code shows how to handle form submit button action.

$(“#form1”).submit(function() {
// validation begin before submit
});

Here I’ve used the pseudo ID to select the HTML form. Once it is selected we can use the “submit” function. Submit function is equal to onSubmit event of the html Form control. This event will be generated when the user clicks on submit button. Once it is generated client side validations for input text box should perform. Since we need to perform the same validation for the other two events as well, the best solution will be to create separate function to perform validation to text box. We can generalize the validation of text box into one central location, which lead to easy maintenance of code by using this approach.Your submit event handler code will be as follows;

//first validation on form submit
    form.submit(function() {
        // validation begin before submit
        if (validateName()) {
            return true;
        } else { return false; }

    });


If the “validateName” returns true form, it will be submitted else display client side error messages

Blur event

Same validate function can be called inside the blur event handler. You can add below code to create blur event validate;

name.blur(validateName);


KeyDown event

As shown above add below code to handle keyup;

name.keyup(validateName);

Building validation function

Inside event handler it is needed to identify what validations need to check. For a given text field validation you may need to check for empty entries, unwanted characters such as numbers (eg. You may not input numbers to a name) and the length.

Validation for empty

Empty validation can be performed using Jquery as follows;

//validation for empty
  if (name.val() == "") {
      name.addClass("error"); // adding css error class to the control
      nameInfo.text("Names cannot be empty!");//filling up error message
      nameInfo.addClass("error");//add error class to info span
      return false;
  } else {
      name.removeClass("error");
      nameInfo.text("*");
      nameInfo.removeClass("error");
        }

The code above demonstrates the use of variables declared above. The Jquery function val() read the input control value prpperty. First condition is to check for empty values. If the input control value is empty then display the error status to the user. Error status can be implement using CSS classes and Jquery. addClass() and text() functions of JQuery provide grate control, using addClass() we can add a CSS class into any HTML tag. Here we add error class to both nameInfor span and name input box. Now the input box and error text are highlighted. Using text() function we write a specific text into HTML control, in this case we write it for span. Finally the function returns false and no submission will happen. Error status will be shown as below.

Validation for empty strings
Validation for empty strings

If the value is not empty then change both controls into normal status. We can achieve this using removeClass() and text() functions. removeClass() function can be used to remove any CSS classes from an html control. Here we use it to remove error CSS class and text() function. It will insert the normal text status to message span.

Validation for length

Length validation is needed to perform for all the text. For example names cannot have only one letter it should be more than two. The code shown below demonstrates how to perform length validation.

	//if it's NOT valid
        if (name.val().length < 2) {
            name.addClass("error");
            nameInfo.text("Names with more than 2 letters!");
            nameInfo.addClass("error");
            return false;
        }
        //if it's valid
        else {
            name.removeClass("error");
            nameInfo.text("*");
            nameInfo.removeClass("error");
            //return true;
        }

Here, the code logic is similar to what we use for empty validation. But only difference is the use of length property. JQuery val() function will read the string value of the html control and JQuery length property. You can decide the text length. Condition will test out for required length and the error logic shown will be the same.

Validation for Length
Validation for Length

Validation for character only

Character validation will be a bit tricky. The code mentioned below will demonstrate how to perform it.

	// validation only for characters no numbers
        var filter = /^[a-zA-Z]*$/;
        if (filter.test(name.val())) {
            name.removeClass("error");
            nameInfo.text("*");
            nameInfo.removeClass("error");
            return true;
        }
        else {
            name.addClass("error");
            nameInfo.text("Names cannot have numbers!");
            nameInfo.addClass("error");
            return false;
        }

Now, an extra parameter called filter is used to store the regular expressions. To filter strings for certain patterns, regular expressions are very useful. E.g. Matching telephone number patterns, email address, date patterns etc. Now we have got the regular expression in a variable. So it is time to make use of the text() function as javascript matches the string. The test() method checks for a match in a string. This function returns a Boolean. For a matching string it provides true, where we can clear an error status. The code will show an error if a mismatch takes place as shown below image.


Validation for numbers
Validation for numbers

Let’s check everything together. HTML code will be as follows;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <link href="style.css" rel="Stylesheet" media="all" />
    <!--step one-->

    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

    <!--step four-->

    <script type="text/javascript" src="js/single.js"></script>

</head>
<body>
    <!--step two-->
    <form id="form1" action="" method="post">
    <!--step three-->
    <div>
        First Name
        <input id="txtname" type="text" />
        <span id="infotext">*</span><br />
        <input id="Submit1" type="submit" value="submit" />
    </div>
    </form>
</body>
</html>


Javascript code will be as follows;

// JScript source code
$(document).ready(function() {
//global variables
var form = $("#form1");
var name = $("#txtname"); //textbox u are going to validate
var nameInfo = $("#infotext"); //to display error message
//first validation on form submit
form.submit(function() {
// validation begin before submit
if (validateName()) {
return true;
} else { return false; }
});
//declare name validation function
function validateName() {
//validation for empty
if (name.val() == "") {
name.addClass("error");
nameInfo.text("Names cannot be empty!");
nameInfo.addClass("error");
return false;
} else {
name.removeClass("error");
nameInfo.text("*");
nameInfo.removeClass("error");
}
//if it's NOT valid
if (name.val().length < 2) {
name.addClass("error");
nameInfo.text("Names with more than 2 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
name.removeClass("error");
nameInfo.text("*");
nameInfo.removeClass("error");
}
// validation only for characters no numbers
var filter = /^[a-zA-Z]*$/;
if (filter.test(name.val())) {
name.removeClass("error");
nameInfo.text("*");
nameInfo.removeClass("error");
return true;
}
else {
name.addClass("error");
nameInfo.text("Names cannot have numbers!");
nameInfo.addClass("error");
return false;
}
}
});


Take a look at the live demo here.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Nikhil 

      2 years ago

      where is style.css

    • expertscolumn profile image

      Stanley Soman 

      5 years ago from New York

      very interesting, i shall consider this, i have to revisit this article when i get to doing this

      thanks

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)