1

I wonder why HTML5 has not yet implemented this simple validation to input number

Here's my snippet. I can't enter. (period) and - (negative)

$('input[type="number"]').on('keypress', function(e){
    if (e.which < 48 || e.which > 57)
        {
            e.preventDefault();
            return false;
        }               
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" step="any" min="0" name="refund" class="form-control" >

But when I tried to enable keyCode for the period, I can input a lot of period in the text box.

$('.allow-decimal').on('keypress', function(e){
    if (e.which == 190)
        {
            return true;
        }               
 });
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
Vahn Marty
  • 1,428
  • 3
  • 14
  • 28
  • Possible duplicate of [jquery only allow input float number](https://stackoverflow.com/questions/6421639/jquery-only-allow-input-float-number) – Albert Einstein Sep 13 '18 at 04:27
  • 1
    But...the validation *works*. You are allowed to input, say, `1...2` but then it's marked as incorrect when the field loses focus. The jQuery code is irrelevant here. – VLAZ Sep 13 '18 at 04:29
  • not really a duplicate, just uses jquery, but could be boiled down to just html input type number. input type number seems like it should be input type int if you can't use decimals and can't turn off negative values using the min attribute – Nateous Sep 13 '18 at 04:29
  • 1
    @Nate neither of these is true: an input of `4.2` is accepted as valid, an input of `-1` is marked in red as invalid [here is a demo](https://jsbin.com/jisujamujo/edit?html,js,output) - note that there is no JS, just HTML5 in play. – VLAZ Sep 13 '18 at 04:32
  • I think the key here is to check for `isNaN()` and apply your validation accordingly. – Saurabh Tiwari Sep 13 '18 at 06:37
  • I think you can do it in 2 steps, capture the current value of input say in 'keydown' event, then validate your input's new value on 'keyup', if fail, replaced the input's value by old value – lucas Sep 13 '18 at 06:56
  • @vlaz you are correct, I think I misunderstood, thanks for the clarification! – Nateous Sep 13 '18 at 13:40

2 Answers2

0

There are something in html you could use..

<form>
 Quantity (between 0 and 100): <input type="number" name="quantity" min="0" max="100" step=".01">
<input type="submit">
</form>
Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
0
<input type="text" onfocus="this.oldvalue = this.value;" onkeyup="validateInput(this);this.oldvalue = this.value;" onchange="validateInput(this);this.oldvalue = this.value;" />

above one is inspired from this question will capture the old value for restore purpose and then

function validateInput(input){
      if(isNaN(input.value)||input.value<0)
      {
        input.value = input.oldvalue;
      }

    }

this one should work

lucas
  • 503
  • 2
  • 13