-1

How to restrict input textbox, restriction of:

  • only numbers
  • only 1 period
  • can put negative/minus sign on the beginning only
Momar
  • 177
  • 1
  • 2
  • 10

2 Answers2

1

Here is the code:

HTML:

<input type="text" id="main"></input>

Javascript:

var main = document.getElementById('main');
main.onkeydown = codeFunc;

function codeFunc(e) {
    var code = e.which || e.keyCode;
    var value = e.currentTarget.value;
    var letter = String.fromCharCode(code);
    codeFunc.isNegative = value.indexOf("-") > -1;
    codeFunc.isMiddle = value.length != 0;
    var letter = String.fromCharCode(code);
    if (letter == "-" && !codeFunc.isNegative && !codeFunc.isMiddle) {
        codeFunc.isMiddle = true;
        codeFunc.isNegative = true;
        return true;
    } else if (letter == "¾" && !codeFunc.isDecimal) {
        codeFunc.isMiddle = true;
        codeFunc.isDecimal = true;
        return true;
    }
    var test = /[\d\b]+/.test(letter);
    if (!codeFunc.isMiddle) {
        codeFunc.isMiddle = test;
        return codeFunc.isMiddle;
    }
    return test;
}

JSFIDDLE

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
0

You can use a regular expression to validate input on the keydown event of a text box:

REGEX

/^-?\d{2}(\.\d+)?$/

As a side note do some research into JavaScript and jQuery.

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71