...

View Full Version : NaN



ez4ne12c
05-01-2004, 06: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?
thanks
ez

Philip M
05-01-2004, 07: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)

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

Philip M
05-01-2004, 05: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".

nolachrymose
05-01-2004, 06:10 PM
if(!(isNaN(parseInt(document.getElementById('user_response').value))))

Hope that helps!

Happy coding! :)

Philip M
05-02-2004, 09: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()}

nolachrymose
05-02-2004, 12:50 PM
Hmm...

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, 04:50 PM
So 123.XYZ is an acceptable or "valid" entry?

Hmm....

nolachrymose
05-02-2004, 06: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