How to Allow Only Numeric Value Using jQuery

, , Leave a comment

As web developers validate user inputs is a regular work in your project. So it will be a good idea if you go for client site solution. For example you have a text field for entering the age of the user and you want to confirm that a numerical value is entered in it and no character or symbol is entered.

We will start with Mark up

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

 

Styling with CSS

Create "Style.css" file in "css" folder. All our css styling will go to this file. Place the following code under title.

<link href="css/Style.css" rel="stylesheet" type="text/css" />

 

Simple CSS

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

 

JavaScript

Download jquery-1.6.4.min.js

Create NumericField.js in "js" folder. Place the following code under title.

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

 

Open NumericField.js in "js" folder. Place the following code:

$(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();  }  }  });  });

 

In the above example the error message in 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 text-input 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 the numeral 0 (ASCII value of 48) or more than the numeral 9 (ASCII value of 57), meaning it is not a numerical value, then 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 the error message Only numerals allowed.

 

Allowing Negative Values

Sometimes while entering numerical values, you have to deal with negative values. In the preceding jQuery code, no symbol is allowed; it means we cannot use a hyphen or minus sign. Hence we cannot enter a negative value in the text field with the existing code. Let's modify our jQuery code to accept negative values:

$(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();  }  }  });  });

 

In the above example the error message is hidden at the beginning.

The event-handling function of the click event attached to the Submit button extracts the data from the text-input field and stores it 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 whether the first character has an ASCII value of 45 (which is the ASCII value of the 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 we saw earlier: checking if the characters in the data variable are numerical values and the values are not numerical displaying the error message.

 

Allowing a Range of Values

Sometimes you want to allow number range in your form; for example if an age below or above the given range is entered; you want an error message to be displayed on the screen. The jQuery code for entering a numerical value between 5 and 99 is shown here:

$(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 first make the error message invisible.

Then we attach the click event to the Submit button. The event-handling function of the click event does several jobs, such as extracting the numerical value entered in the text-input 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 contents in data has an ASCII value lower than the numeral 0 (ASCII value of 48) or greater than the numeral 9 (ASCII value of 57), it means the data variable contains some value other than a numerical value, so 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 we exit from the for loop.

If the value of the 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; It means, whether it is between 5 and 99.

So, if the value of the flag variable is 0 (after the execution of the for loop; that is, after inspecting all characters of the data variable), it means the data entered is valid and consist only of numerals; we then apply the conditional statement that the numeral may not be less than 5 or greater than 99, then make the error message visible and set the 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 if the value is not within the range

Share this:
 

Leave a Reply