I have this code that only permits numbers to be entered in an input field on keypress()
if (e.which != 8 && e.which != 0 && (e.which < 48 ||
This solution prevents double minuses or dots.
Just add number to input class.
$("input.number").on('keypress', function(e) {
var caret = e.target.selectionStart;
var nowStr = $(this).val().substr(0, caret) + String.fromCharCode(e.which) + $(this).val().substr(caret);
if (!$.isNumeric(nowStr)) e.preventDefault();
});
$('.DecimalNumberWithNegative').keypress(function (event) {
NumberPostiveNegativeWithDecimal(event, this)
});
$('.DecimalNumberWithNegative').keyup(function (event) {
ReplaceNegative(event, this);
});
function NumberPostiveNegativeWithDecimal(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (
(charCode != 45 || $(element).val().indexOf('-') != -1) &&
(charCode != 46 || $(element).val().indexOf('.') != -1) &&
(charCode < 48 || charCode > 57))
evt.preventDefault();
return true;
}
function ReplaceNegative(event, element) {
var $$this = $(element).val();
//alert($$this);
var charCode = (event.which) ? event.which : event.keyCode
if (charCode == 189 && $$this.indexOf('-') > 0) {
value = $$this.replace('-', '');
$(element).val(value);
event.preventDefault();
}
}
Here is a working demo that checks whether the number is valid or not and also doesn't allow multiple signs:
$("#num").on('keyup', function() {
if ($.isNumeric($(this).val())) {
console.log('Valid!');
} else {
console.log('Invalid!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="num" />
This is a solution, but I recommend to use mask plugin, for example: jQuery-Mask-Plugin
$("#id").keypress(function(e){
if (e.which != 46 && e.which != 45 && e.which != 46 &&
!(e.which >= 48 && e.which <= 57)) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id" />