0

我正在尝试验证一个文本框以允许所有正数,包括其中的 -1。

我试过这个,这将只允许正数

  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;
    }

但是如何允许-1(仅)所有正数提前谢谢

4

1 回答 1

1

为什么不验证和清理输入,而不是防止击键?也许是这样的:

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

    txtBox.value = val;
}
于 2012-05-08T12:34:18.700 回答