JavaScript is an integer test

I have a text box that allows the user to enter their age. I am trying to do some client side validation in this field using JavaScript. I already have server side validation. However, I cannot verify that the user is entering the actual integer. I am currently trying to execute the following code:

function IsValidAge(value) { if (value.length == 0) { return false; } var intValue = parseInt(value); if (intValue == Number.NaN) { return false; } if (intValue <= 0) { return false; } return true; } 

Honestly, I entered individual characters in a text field of type "b", and this method returns true. How can I guarantee that the user enters only an integer?

thank

+78
javascript
Jun 19 '09 at 18:50
source share
11 answers

UPDATE

I fixed the error code and added var named key to save the pressed code using keyCode and which are browser dependent.

 var key = e.which || e.keyCode; 

Thanks Donald.McLean :)




If you want to check whether you write down numbers during input (and do not write other characters in the input field), you can use this simple function and you can define the allowed elements (including everything that you want to filter). Thus, you can choose not only integers, but, for example, a certain group of characters. The example is based on jQuery to attach it to an input field.

 $('#myInputField').keypress(function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) && // Interval of values (0-9) (key !== 8) && // Backspace (key !== 9) && // Horizontal tab (key !== 37) && // Percentage (key !== 39) && // Single quotes (') (key !== 46)) // Dot { e.preventDefault(); return false; } }); 

If you use a key other than a specific one, it will not appear in the field. And since Angular.js is getting strong these days. this is a directive that you can create for this in any field of your web application:

 myApp.directive('integer', function() { return function (scope, element, attrs) { element.bind('keydown', function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) && // Interval (0-9) (key !== 8) && // Backspace (key !== 9) && // Horizontal tab (key !== 37) && // Percentage (key !== 39) && // Single quotes (') (key !== 46)) // Dot { e.preventDefault(); return false; } }); } }); 

But what happens if you want to use ng-repeat , and you need to apply this directive only in a certain number of fields. Well, you can convert the top directive into one prepared in order to recognize the value true or false in order to be able to decide which field will depend on it.

 myApp.directive('rsInteger', function() { return { restrict: 'A', link: function (scope, element, attrs) { if (attrs.rsInteger === 'true') { element.bind('keydown', function(e) { var key = e.which || e.keyCode; if (!(key >= 48 && key <= 57) && // Interval (0-9) (key !== 8) && // Backspace (key !== 9) && // Horizontal tab (key !== 37) && // Percentage (key !== 39) && // Single quotes (') (key !== 46)) // Dot { e.preventDefault(); return false; } }); } } } }); 

To use this new directive, you just need to do this in input type text, for example:

 <input type="text" rs-integer="true"> 

Hope this helps you.

+8
Sep 12 '13 at 6:58 on
source share
 var intRegex = /^\d+$/; if(intRegex.test(someNumber)) { alert('I am an int'); ... } 

This will be absolutely, positive if the user enters anything other than a non-negative integer.

+132
Jun 19 '09 at 18:53
source share

For int authentication use this:

 function isInt(value) { return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10)); } 

The problem with many int checks is that they return 'false' for 1.0, which is a valid integer. This method checks that the values ​​of float and int parsing are equal, so for # .00 it will return true.

UPDATE:

In the comments, we discussed two questions that I will add to future readers:

  • First, when analyzing string values ​​that use a comma to indicate a decimal place, this method does not work. (No wonder how could this be? Given "1001", for example, in the USA it is an integer, but in Germany it is not.)
  • Secondly, the behavior of parseFloat and parseInt has changed in some browsers since this answer was written and varies depending on the browser. ParseInt is more aggressive and discards letters that appear on the line. This is great for getting a room, but not very good for checking.

My recommendation and practice is to use a library like Globalize.js to analyze numerical values ​​for / from the user interface, and not to implement a browser, and to use your own calls only for known "programmatically" provided values, such as a string parsed from an XML document.

+31
Jun. 19 '09 at 19:02
source share

use isNaN (n)

i.e.

 if(isNaN(intValue)) 

instead

 if (intValue == Number.NaN) 
+13
Jun 19 '09 at 18:55
source share

I did this to check the number and integer value

 if(isNaN(field_value * 1) || (field_value % 1) != 0 ) not integer; else integer; 

Modular Divison

Example
1.25.5% 1! = 0 and,
2.25% 1 == 0

And if (field_value * 1) NaN, if the string eg: 25.34 or abcd, etc. .... else integer or number

+4
Dec 02 '13 at 9:52
source share

function isInt (x) {return Math.floor (x) === x;}

+2
Apr 08 '14 at 15:01
source share

If your number is in a 32-bit integer range, you can go with something like:

 function isInt(x) { return ""+(x|0)==""+x; } 

A bitwise or statement action converts to a signed 32-bit int. Converting strings on both sides ensures true / false.

+1
Mar 04 '14 at 16:46
source share

No one tried this simple thing?

 function isInt(value) { return value == parseInt(value, 10); } 

What is wrong with this?

+1
Jun 05 '15 at 10:10
source share

You can use the isInteger() method of the Number object

 if ( (new Number(x)).isInteger() ) { // handle integer } 

This method works correctly if x is undefined or null . But he is a poor support browser at the moment

0
Apr 16 '14 at 3:55
source share

I found NaN's answers missing because they do not pick up trailing characters (so "123abc" is considered a valid number), so I tried converting the string to an integer and returning to the string and making sure it matches the original after the conversion:

 if ("" + parseInt(stringVal, 10) == stringVal) { alert("is valid number"); } 

This worked for me until the numbers were so big that they began to appear as scientific notation during the conversion.

... therefore, of course, this means that you can enter a number in scientific notation, but checking the minimum and maximum values ​​will also prevent this if you wish.

Of course, this will happen if you use delimiters (for example, "1000" or "1.000" depending on your locale) - numbers are allowed only here.

0
Jul 24. '14 at 10:12
source share
 If (enteredAge < "1" || enteredAge > "130") ...... 

Simple and it works ... until they develop immortality

-3
Aug 11 '14 at 19:37
source share



All Articles