Search code examples
javascriptinternet-explorer-7

javascript in IE7, number (integer) validation doesn't work


function isInteger(char) {
    return (char.toString().search(/^-?[0-9]+$/) == 0 )
}
function validateQuan() {
var minExist = "false";
    for (i=0; i<3; i++) {
        var j = document.getElementById("ProductQuantity_"+i).value; 
        if (isInteger(j) && j > 0) {minExist = "true";alert("oi");} 
    }
    if (minExist == "true") {$("#pvs_form").submit();} else {alert("Please enter at least one valid quantity");}
}

Above is my code, it's working on FF 3.6 and IE8, but not with IE7. At IE7 "if (isInteger(j) && j > 0)" couldn't lead to "true". Even i remove "j > 0" and use "[1-9]" on regex.

Any better solution?

edit : sorry, the regex is wrong, any number > 9 is "true" too.

edit : big sorry to all, i just found that the main problem actually because i got other form at the same page with the same id "ProductQuantity_"+i, and likely it turn the IE7 to only look at the first element with that id found on page. Maybe my original code was working actually, but thx to remind me that the regex is not as expected and to get better code. Thx and sorry once more.


Solution

  •    var isInteger = function( str ) { 
          return  (str|0) == str;
        };
    

    Bitwise OR by 0 ensure that, string or number with floating point is replaced to integer

    isInteger("3.4") // false
    isInteger("abc") // false => "abc"|0 = 0
    isInteger("3") // true
    

    And now:

    function validateQuan() {
        var minExist = false ;
        for (var i = 0; i < 3; i++ ){
            var j = document.getElementById("ProductQuantity_"+i).value; 
            if ( isInteger( j ) && j > 0 ) {
                minExist = true; 
                alert("oi");
                break; // goal achieved, break loop
            } 
        }
        if ( minExist ) {
            $("#pvs_form").submit();
        } else {
            alert("Please enter at least one valid quantity");
        }
    }