user1295132
user1295132

Reputation:

javascript validation for allow -1 and all positive numbers in text box

I am trying to validate a text box to allow all positive numbers including -1 in it.

i tried this, which will work for allowing only positive numbers

  function allownumbers(e, txtBox) {
        var key;

        key = (e.keyCode) ? e.keyCode : e.charCode;
        if (e.charCode == 0) {
            return true;
        }
        if ((key < 48 || key > 57) && (key != 46) && (key != 44)) {               
            return false;                
        }
        if (key == 46) {
            if ((txtBox.value).indexOf('.') != -1) {
                return false;
            }
        }
        if (key == 44) {
            if ((txtBox.value).indexOf(',') != -1) {
                return false;
            }
        }
        return true;
    }

But how to allow -1(only) with all positive numbers Thanks in advance

Upvotes: 0

Views: 1347

Answers (1)

Nadh
Nadh

Reputation: 7253

Instead of preventing keystrokes, why not validate and sanitize the input? Maybe something like this:

function allownumbers(e, txtBox) {
    var val = parseInt(txtBox.value);
    if(!val || val < -1) {
        val = 0; // invalid value, reset to zero
    }

    txtBox.value = val;
}

Upvotes: 1

Related Questions