Ad

Jquery - Allow Only Negative, Positive Or Decimal Number Validation In Field

- 1 answer

I use this code for positive validation of numbers and decimal. Now I would like to allow also negative numbers and decimals but it is not working. Any idea please?

$('.number_only').keypress(function(e){
    return isNumbers(e, this);      
});

function isNumbers(evt, element) 
{
  var charCode = (evt.which) ? evt.which : event.keyCode;
  if (
        (charCode != 46 || $(element).val().indexOf('.') != -1) &&      // “.” CHECK DOT, AND ONLY ONE.
        (charCode < 48 || charCode > 57)
     )
  return false;
  return true;
}

I found this but no idea how to implement it jquery - allow only negative, positive or decimal number validation

Ad

Answer

You can use regex instead to solve your problem, change your method to something like this:

function isNumbers(evt, element) 
{
     var elementValue = $(element).val();
        var regex = /^(\+|-)?(\d*\.?\d*)$/;
        if (regex.test(elementValue + String.fromCharCode(evt.charCode))) {
            return true;
        }
        return false;
}
Ad
source: stackoverflow.com
Ad