简体   繁体   中英

checking for integer input on button click

I am trying to get this Javascript in my application working.

function validateQuantity(field)
{
    var value = field.value; //get characters
    //check that all characters are digits, ., -, or ""
    for(var i=0;  i < field.value.length; ++i)
    {
        var new_key = value.charAt(i); //cycle through characters
        if(((new_key <= "0") || (new_key > "9")) &&
            !(new_key == ""))
        {
            alert("Please enter number and greater than 0 only");
            return false;
            break;
        }
        return true;
    }
}

And I have a input button as below

<input class="buttonToLink" type="submit" value="Update" 
       onclick="return validateQuantity(document.getElementById('quantity'))"/>

The above code successfully checks the input of all alphabet such as "abc" or alphabet and numeric such as "abcd123" as false.

However, when I put numeric characters first, along with alphabet such as "123abc", it fails -- it does not show the alert.

What did I do wrong with the code, and how can it be fixed?

if (parseInt(new_Key) == new_Key) {
    //valid
} else { // it will return NaN
    //invalid
}
function validateQuantity(field) {
    if (!/^\d+$/.test(field.value)) { // is an integer
       alert("Please enter number and greater than 0 only");
       return false;
    }

    return true;
}

The reason your code doesn't work is because you have the return true statement inside the loop. As soon as it sees a valid integer it will return true and break out of the function, ignoring anything that comes after it. Allowing strings like "123abc" for example.

This is probably what you wanted:

function validateQuantity(field)
{
    var value = field.value; //get characters
    //check that all characters are digits, ., -, or ""
    for(var i=0;  i < field.value.length; ++i)
    {
        var new_key = value.charAt(i); //cycle through characters
        if(((new_key <= "0") || (new_key > "9")) &&
            !(new_key == ""))
        {
            alert("Please enter number and greater than 0 only");
            return false;
            break;
        }
    }

    return true;
}

Try parsing the value as an integer, and compare with the original value.

var isAllNumbers = (parseInt(field.value) == field.value);

Perhaps use a jQuery selector, and use a regex to test for numeric.

var isAllNumbers = $("#quantity").val().match(/\d+$/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM