0

jquery

$(".numeric").bind("keypress", function (e) {
        var keyCode = e.which ? e.which : e.keyCode
        var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
        return ret;
    });

Html

<input type="text" class="numeric" id ="txt"/>

Here the code is working fine to validate numeric values with decimal.

But I want negative values to be included in the validation like -1.23,-2.23,-37.856,etc.

Note: The - symbol should appear only at the beginning and should be optional.

Pearl
  • 8,373
  • 8
  • 40
  • 59
  • FYI, jQuery `bind` is deprecated in favor of `on` – xGeo May 29 '17 at 11:59
  • Question marked as duplicate doesn't answer whats needed here. This link (https://stackoverflow.com/questions/29977092/only-allow-numbers-decimals-negative) does allow multiple minus sign, and hence doesn't answer this question. – Milan Chheda May 29 '17 at 12:10

1 Answers1

2

Here is an extremely simple demo to help you out:

$("#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" />
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35