Reputation: 7549
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
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
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
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