Testing for Numeric Data

C

Cogito

In a form I have two text fields. In one of them the user enters a
decimal number and in the other a hexadecimal number. What code can be
used to validate that the entered text is numeric and to produce a
warning when it is not.
 
E

Erwin Moller

Cogito said:
In a form I have two text fields. In one of them the user enters a
decimal number and in the other a hexadecimal number. What code can be
used to validate that the entered text is numeric and to produce a
warning when it is not.

Hi Cogito ,


have a look at parseInt(s, radix)
where s is the string to be parsed and radix is optional, but you should use
it to test for hexadecimal strings.

remember that the function parseInt will return NaN (Not A Number) when the
conversion cannot be done.

Good luck.

Regards,
Erwin Moller
 
S

Selrak

Be careful with parseInt, in IE it have a bug, and for 08 or 09 don't have a
good response. If you can, use parseFloat.

Selrak


"Erwin Moller"
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Erwin Moller <since_humans_read_this_I_am_spa
(e-mail address removed)> posted at Thu, 8 Jul 2004 14:33:11 :
have a look at parseInt(s, radix)
where s is the string to be parsed and radix is optional, but you should use
it to test for hexadecimal strings.

But parseInt(S, 10) will accept "10 bananas", which is not a decimal
number. It also accepts 1.999 as meaning 1.
remember that the function parseInt will return NaN (Not A Number) when the
conversion cannot be done.

Input validation is best done with a RegExp; see <URL:http://www.merlyn.
demon.co.uk/js-valid.htm>.

decimal: /^\d+$/
hexadecimal: /^[0-9a-z]+$/i

Use {m,n} where m & n are integers to control the number of digits.

In evaluating the hex string, you may need to prefix it with "0x".

Remember : the aim of the authors of javascript was to attach some
meaning to as many forms of input as possible (dates being a good
example); the aim of the programmer needs to be to ensure that only
unambiguous input of suitable value is accepted, and to interpret it
correctly.
 
L

Lee

Erwin Moller said:
Hi Cogito ,


have a look at parseInt(s, radix)
where s is the string to be parsed and radix is optional, but you should use
it to test for hexadecimal strings.

remember that the function parseInt will return NaN (Not A Number) when the
conversion cannot be done.

That depends on what you consider to be "the conversion".
parseInt("action",16) will quite contentedly convert that
invalid input into the number 172.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top