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
The Number. isInteger() method determines whether the passed value 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With