View Full Version : NaN

05-01-2004, 07:38 AM
How can i detect if a substring represents a valid integer number

my example is something like

if (document.getElementById("user_response").value.substring(0,document.getElementById("user_response").value.indexOf('.'))
!= NaN)

is that sensible?

Philip M
05-01-2004, 08:34 AM
Use a regular expression!

teststring = thesubstringvalueyouwanttotest
if (/\D/.test(teststring)) {
do whatever is wanted if the test fails

\D means "match anything which is not a digit, i.e. not 0-9"

So if a match is found the test fails (returns true here)

05-01-2004, 08:56 AM
Further, you could always make use of the isNaN function.

Philip M
05-01-2004, 06:36 PM
The questioner wished to detect whether a substring represents a valid integer number.

The isNaN function would not reject a real (decimal) number.

I assume that by "valid" the questioner means any integer number, as opposed to certain specific numbers which are considered to be "valid".

05-01-2004, 07:10 PM

Hope that helps!

Happy coding! :)

Philip M
05-02-2004, 10:05 AM
OK, that works as well if the user input is not a number ("xyz"), but if the user enters a real (decimal) number such as 3.14 then parseInt() returns 3, and the validation passes. I understood that the questioner wishes only INTEGER numbers to be entered into the field.

With respect, I still prefer the regular expression!

if(/\D/g.test(this.value)){alert('Only integer numbers are valid in this box. ');this.value='';this.focus()}

05-02-2004, 01:50 PM

From his original code, it seems he is testing to see if the integer part of the value of the field is a number (he is taking the substring from the first character to the decimal place). Am I missing something?

Happy coding! :)

Philip M
05-02-2004, 05:50 PM
So 123.XYZ is an acceptable or "valid" entry?


05-02-2004, 07:42 PM
I don't know - ez4ne12c didn't indicate what should follow the decimal point. He or she might require a special form in the form field.

Happy coding! :)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum