Reputation: 4616
What is the best way to prevent users from entering negative values in an input text element?
Currently I am checking the field value on blur, but I am hoping somebody has a better solution.
$(".payment").blur(function() {
var payment = getAmount($(this).val());
if(!isNaN(payment) && amount >= 0) {
$(this)
.css("color", "black")
.val(currency(payment));
} else {
if(amount < 0) showMessage("Negative amounts are not allowed", "error");
$(this).css("color", "red");
}
});
function getAmount(strAmount) {
var amount = new String(strAmount).replace(/\$/g, "").replace(/,/g, "");
return parseFloat(amount);
}
Upvotes: 2
Views: 16929
Reputation: 253308
On the assumption you might not want to work with key-codes (e.which
, e.keyCode
and so on), here's one further option:
$('#a').blur(
function(){
var v = $(this).val(),
t = parseInt(v,10),
b = isNaN(t);
if (b){
$(this).val('');
}
else {
$(this).val(Math.abs(t));
}
});
References:
Upvotes: 2
Reputation: 4616
Thanks for all of the answers.
Here is what I ended up with:
$("input.payment").keypress(function(e) {
validateNumeric(e);
});
function validateNumeric(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Upvotes: 0
Reputation: 31131
You can use jQuery's keypress or keydown events to test against the input on every key.
If you haveother fields that need validating as well, consider jQuery Validation plugin.
Upvotes: 1
Reputation: 9422
This ought to do the trick:
$(".payment").keydown(function(event) {
if (event.keyCode == 45 ) { event.preventDefault(); }
});
This will prevent the keydown event from registering when the character code for "-" (45) is detected.
Upvotes: 2
Reputation: 6598
You could use jQuery's .keypress()
and prevent the default action for the - key.
Example: http://jsfiddle.net/5cgXg/
$("#target").keypress(function(event) {
if ( event.which == 45 || event.which == 189 ) {
event.preventDefault();
}
});
Upvotes: 9