Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Test for an integer

Tags:

javascript

I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying 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;     } 

The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer?

Thank you

like image 944
user70192 Avatar asked Jun 19 '09 18:06

user70192


People also ask

How do you test if a number is an integer in JavaScript?

The Number. isInteger() method determines whether the passed value is an integer.

How can you tell if a number is an integer?

To check if a String contains digit character which represent an integer, you can use Integer. parseInt() . To check if a double contains a value which can be an integer, you can use Math. floor() or Math.


Video Answer


1 Answers

var intRegex = /^\d+$/; if(intRegex.test(someNumber)) {    alert('I am an int');    ... } 

That will absolutely, positively fail if the user enters anything other than an nonnegative integer.

like image 50
karim79 Avatar answered Sep 18 '22 10:09

karim79