ParPar
ParPar

Reputation: 7549

Allow negative/positive numbers but not letters

I want to disable letters in my textbox, that's why I used this expression:

/^[0-9]*$/

The problem is that I want to allow negative numbers too, and this expression does'nt enable me to use minus sign.(-).. What shuold I do?

Upvotes: 0

Views: 3493

Answers (4)

Samidjo
Samidjo

Reputation: 2355

Use the isNaN() function of JavaScript.

Here is a code below:

$(document).ready(function () {
    numbersPlusMinus();
});


function numbersPlusMinus() {

    var inputPrev = "";

    $(".toNumberPlusMinus").change(function () {

        if (isNaN($(this).val())) {

            $(this).val(inputPrev);

        } else {

            inputPrev = $(this).val();
        }
    });
}

Upvotes: 0

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74380

More correctly: /^(?:- *)?[0-9]+$/

Since it is usually allowed to have one or more spaces between the minus sign and the digits. Also, you must have at least one digit to have a valid number.

Upvotes: 5

e.dan
e.dan

Reputation: 7485

If you decide you want to match all kinds of numbers, including floating point, this is a good read. If you just want to match simple integers with an optional "minus" sign, then go with hsz's answer, though I might change the * to a +.

Upvotes: 0

hsz
hsz

Reputation: 152216

Try with following regexp:

/^-?[0-9]*$/

Upvotes: 9

Related Questions