View Single Post
Old 02-03-2013, 04:47 AM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,168
Thanks: 59
Thanked 3,992 Times in 3,961 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
This is crazy:
Code:
function validInt(value)
{
    for (var i=0; i < value.length; i++) {
        var c = value.charAt(i);
        if ((c < '0' || c > '9') && c != '.') {
            alert("There's a problem: all values herein must " +
                    "be numbers only, and " + value + 
                    " has an unacceptable character " + "'" + c + "'");
            return(false);
       }
    }
    return(true);
}
validInt??? Integers do *NOT* have decimal points, so what in the world is the test for period doing in there?

On top of that, as written that code would *ALLOW* input such as ".........." or "3........9" or "3.999999999999", none of which make a lot of sense.

If you want to check for a valid number--and here I will assume it is to be no more than 2 digits after the decimal point (i.e., dollars and cents) then:
Code:
function validNum( value )
{
    if ( ( /^\-?(\.\d\d?|\d+(\.\d?\d?)?)$/ ).test( value ) { return true; }
    document.getElementById("errorMessage") = 
          "That is not a valid dollars and cents value";
    return false;
}
The \-? in red is optional, if you want to allow negative numbers.

Notice that this also avoids the use of alert( ), which is obsolete.

But if you aren't so fussy--if you *WILL* allow numbers such as 3.9999999 or 13E2--then let JS test for you:
Code:
if ( isNaN( value ) ) { ... not a valid number ... } else { ... valid ... }
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.

Last edited by Old Pedant; 02-03-2013 at 04:50 AM..
Old Pedant is offline   Reply With Quote