Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / jQuery

Validating numerical field in jQuery

3.00/5 (1 vote)
22 Oct 2010CPOL6 min read 55.3K  
In this article, we are going to earn how to validate a numerical field through jQuery.

Take the scenario where the user is allowed to enter only a numerical value and no character or symbol in the input field. If the user enters anything other than the numerical value, he will get an error. The article also explains:



  • how to allow users to enter negative values too
  • how to allow users to enter a range of numerical values

Let us assume that you have an input field for entering the age of the person and you want to confirm that a numerical value is entered in it and no character or symbol is entered.


HTML file for "Validating numerical field in jQuery"


The HTML code to display the form that contains label, input text field, error message and a submit button is as shown below:


<body>
<form id="signup" method="post" action="">   
 <div><span class="label">Enter Age </span><input type="text"  class="infobox" name="age" /><span class="error"> Only numericals allowed</span></div>   
<input class="submit" type="submit" value="Submit">
</form>  
</body>

Since the purpose of the HTML form above is to validate on the input text field and not to send the entered data to some other page for processing, the action attribute of the form is left blank. The form is assigned an id of signup and method is set to post – though it will have no effect on our validation procedure.


The label message User Id is enclosed in a span element of class label. The input text field is assigned a class name infobox and the error message ("This field cannot be blank") is stored as a span element of class error and finally the submit button is assigned the class submit.


The reasons of assigning the classes to all the four items of the form is to apply the properties defined in the class selectors .label, .infobox, .error and submit (defined in the style sheet: style.css) to be applied automatically to the respective four items of the form. The style sheet with the respective class selectors is as shown below:

style.css
.label {float: left; width: 120px; } 
.infobox {width: 200px; } 
.error { color: red; padding-left: 10px; }
.submit { margin-left: 125px; margin-top: 10px;}

Allowing only numerical values


Code for "Validating numerical field in jQuery"


The jQuery code to check that the age entered in the text field contains only numerical values and no text or symbol is as shown below:


$(document).ready(function() {   
  $('.error').hide();
  $('.submit').click(function(event){
    var data=$('.infobox').val();
    var len=data.length;
    var c;
    for(var i=0;i<len;i++)
    {
      c=data.charAt(i).charCodeAt(0);
      if(c <48 || c >57)
      {
        $('.error').show();
        event.preventDefault();
        break;
      }
      else
      {
        $('.error').hide();
      }
    }
  });
});

Allowing negative value also


Sometimes it happens that while entering numerical values, we come across negative values also. In the above jQuery code, no symbol is allowed i.e. we cannot use – (hyphen or minus) hence we cannot enter a negative value in the text field with the above code. Let us modify our jQuery code to accept negative values also:


Code for "Validating numerical field in jQuery"


$(document).ready(function() {   
  $('.error').hide();
  $('.submit').click(function(event){
    var data=$('.infobox').val();
    var len=data.length;
    var c;
    for(var i=0;i<len;i++)
    {
      c=data.charAt(i).charCodeAt(0);
      if(c==45 && i==0)
      {
        continue;
      }
      if(c <48 || c >57)
      {
        $('.error').show();
        event.preventDefault();
        break;
      }
      else
      {
        $('.error').hide();
      }
    }
   });
 });

Allowing a range of values


You want to enter the age of the person and want it to be within the range 5 to 99 i.e. if the age is entered below or above the given range, you want an error message to be displayed on the screen.


The jQuery code for entering the numerical value between the range 5 to 99 is as shown below:


Code for "Validating numerical field in jQuery"


$(document).ready(function() {   
  $('.error').hide();
  $('.submit').click(function(event){
    var data=$('.infobox').val();
    var len=data.length;
    var c=0;
    var age=0;
    var flag=0;
    for(var i=0;i<len;i++)
    {
      c=data.charAt(i).charCodeAt(0);
      if(c <48 || c >57)
      {
        $('.error').show();
        flag=1;
        event.preventDefault();
        break;
      }
      else
      {
        $('.error').hide();
      }
    }
 
    if(flag==0)
    {
      age=parseInt(data);
      if(age<5 || age>99)
      {
        $('.error').show();
        $('.error').text('Invalid Age. Please enter the age within the range 5 to 99');
        event.preventDefault();
      }
    }
  });
 });

We can see in the above HTML file that the label is set to display the text ‘Enter Age’ and error message is assigned the text: ‘Only numericals allowed’. Also, the four items: label, input text field, error message and submit button are assigned different class names (label, infobox, error and submit) so as to apply the properties defined in the class selectors (defined in the style sheet: style.css) to them.


We can see in jQuery code of ‘Allowing only numerical values’, that the error message is initially set to invisible. The click event is attached to the submit button so as to execute its event handling function if the submit button is clicked. In the event handling function, we see that the data in the input text field (the text field is enclosed in the span element of class infobox) is retrieved and is stored in a variable called data. Its length is calculated and a for loop is executed up till the length of the input data to parse each of its individual characters.


In the for loop, we take one character at a time (of the input data) and with the help of charCodeAt()find its ASCII value. If the ASCII value of the character is below 48 (ASCII value of 0) or more than 57 (ASCII value of 9), meaning it is not a numerical value, we make the error message visible on the screen and exit from the loop. The preventDefault() method of the event object is used to prevent the data entered by the user from being sent to the server or the user navigating to the target form.


On execution of the program, if we enter some characters after the age, we get an error message: ‘Only numericals allowed’ as shown in below given figure:



Error message displayed if character appears after tha age

Even if the character appears in between the digits, the error will be displayed as shown in below given figure:



Error message displayed if the character applears in between the numericals

Also, if we add any symbol, like minus or underscore, we get the error message displayed as shown in below given figure:



Error message displayed on entering symbols.

We can see in jQuery code of ‘Allowing negative value also’, that error message is made hidden at the beginning. The event handling function of the click event attached to submit button, extracts the data from the input text field and stores in variable data. Each individual character stored in data is parsed with the help of a for loop. In the loop, we convert each character in the data variable to its ASCII value and check that if the first character has ASCII value of 45 (which is ASCII value of minus sign) then continue checking the rest of the characters without displaying any error message. The second condition in the for loop is the one that we saw earlier i.e. checking if the characters in the data variable are numerical values and displaying the error message if not.


In the jQuery code of ‘Allowing a range of values’, we first make the error message invisible. Then attach the click event to the submit button. The event handling function of the click event does several jobs like extracting the numerical value entered in the input text field (assigned the class name infobox) and storing it in the variable data. We then find out the length of the data and execute the loop to parse each of its individual characters. If any of the individual contents in data has ASCII value lower than 48 (ASCII value of 0) or greater than 57 (ASCII value of 9), it means the data variable contains some value other than a numerical value, hence we make the error message visible. Also we set the value of a variable flag to 1 to indicate that only numbers are allowed and exit from the for loop. If the value of flag is set to 1, it means there is no point in checking the range of the numerical value as it is invalid data.


If the data is a number, we need to check the range of the numerical value i.e. whether it is between 5 and 99. So, if the value of the flag variable is 0 (after the execution of the for loop i.e. after inspecting all characters of the data variable), it means the data entered is valid and consist only of numerical digits; we then apply the conditional statement that if it is less than 5 or greater than 99, then make the error message visible and set the test of error message to ‘Invalid Age’. The preventDefault() method of the event object is used for preventing submission of the entered data in case it is invalid. We may get the error message displayed as shown in blow given figure if the value is not within the range 5 and 99



Error message displayed if the value is not within the range 5 to 99

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)