A proposal for a possible FAQ subsection - numeric input

D

Dr John Stockton

The present FAQ does not AFAICS directly and fully answer the
frequently-implied question :
"How should I input and check a number?"

The scenario is that document.forms["Frm3"].InputID.value contains a
string, and the numeric meaning of the string is to go into the variable
InputValue. If no checking is needed, and leading/trailing spaces are
irrelevant (and Octal is not needed but Hex need not be prevented), then
I think we might agree that
InputValue = + document.forms["Frm3"].InputID.value
does nicely.

If there is to be validation, ISTM that "isNaN-grade" checking is rarely
adequate, except for "scientific" applications. Normally, one or more
of the following or similar must apply :

The number is non-negative, and non-empty
The number does not use e-format
The number is integer, not allowing such as 3.00
The integer part of the number has m..n digits
The fractional part of the number has m..n digits
The fractional part is optional
The fractional part is compulsory
and
The value must lie in a given numeric range, less than that
implied by the number of digits.

The last is easily accommodated by a test on a type Number, must not be
forgotten, and needs little further consideration.

A currency sign, or other form of unit designator, may be
permitted/mandatory; leave that case aside for now.

I assert that the validation and conversion is best done by

T = document.forms["Frm3"].InputID.value
// Use a RegExp on T
// If error, prompt and go back
InputValue = + T
or InputValue = + RegExp.$n // for n in 1..

noting that some systems may need an alternative for RegExp.$n .

We can now present a structure, and some RegExps to put in it.

The structure should, I think, involve as onclick="ClickA()" or
similar, with something like
function ClickA() {
// if Field1 is bad, warn & return
// if Field2 ...
// Call the actual job
}

RegExps Examples :
/^\d+$/ All-digit
/^\s*[-+]?\d+\s*$/ Unbroken Signed integer & spaces
/^\d{1,5}$/ 1 to 5 digits
/^\d+\.\d\d$/ Money
/^\d+(\.\d{2})$/ Money


I don't know if that, by removing the reasoning, can be boiled down to
suitable size, or whether it would be better on a Web page.

Can one write a general numeric field checker, with three parameters for
input, RegExp, and Output? Or with triads of parameters, one per field?

::::

Footnote : Section 4.12, on parseInt('09') :
How about adding a sentence :
"The unary + operator often suffices : +'09' gives 9, of type Number.".
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top