Entry
How do I check to see if text field has a valid number allowing decimals?
Feb 12th, 2001 07:08
Iván Rivera, Juergen Thelen, Kraig Johnston,
This depends on how low you gonna set your minimum required javascript
version...
If you want to support JavaScript 1.2 and up (i.e. NN4.06+ and IE4+ for
example) browsers only, you are able to use regular expressions and its
test() method for checking.
Example:
var allValid = /[0-9.]/g; // but see below...
if (allValid.test(document.MyForm.MyTextfield.value))
{
// your textfield consists of digits a points only
}
else
{
// your texfield
}
Regular expressions are way too complex to describe them here, so if
you're not yet familiar with them, better have a look at:
http://developer.netscape.com/docs/manuals/js/client/jsguide/regexp.htm
If you decide to lower your minimum javascript requirements down to
JavaScript 1.1, you can't use regular expressions anymore (since they
were implemented first in JS 1.2).
With JavaScript 1.1 you can check your textfields contents with some of
the top-level functions like isNaN(), parseFloat() and parseInt(). Each
of this functions has its advantages and disadvantages. Usually you
will have to use combos of them to make waterproof checkings...
Check this URL to learn more about top-level functions:
http://developer.netscape.com/docs/manuals/js/client/jsref/toplev.htm
Hope this helps.
Juergen
P.S.: the regular expression used in the example catches all POSITIVE
numbers, but not negative ones. Moreover, strings like "42.42.42" would
qualify as a number... You should use a slightly more complex regular
expression:
validNumber = /^-?[0-9]*(\.[0-9]+)?$/
Even that has some problems: for example, it allows as valid numbers
things like -00.0, but since parseFloat() doesn't choke on it (returns
0, as expected), I think it's safe enough. At least everything you might
feed to that little beast is assured to be a real number, if
validNumber.test() returns true.
Iván