Restrict user to put value in range in html input (type = number)

后端 未结 4 2005
清歌不尽
清歌不尽 2021-01-06 01:41

How can I stop user from adding number greater than max value and smaller then min value in html input(type = number)



        
相关标签:
4条回答
  • 2021-01-06 02:16

    Set value to min...

    <form>
    <input id="ageRange" type="number" min="20" max="50" value="20"></input>
    </form>
    
    0 讨论(0)
  • 2021-01-06 02:21

    You would need handle input at a low level and perform your own checks. To prevent the user from typing value larger than the maximum, you could handle the keypress event and then check the input character and whether it would make the value too large:

    <input id="ageRange" type="number" min=20 max= 50 maxlength=2>
    <script>
    document.getElementById('ageRange').onkeypress =
      function (e) {
        var ev = e || window.event;
        if(ev.charCode < 48 || ev.charCode > 57) {
          return false; // not a digit
        } else if(this.value * 10 + ev.charCode - 48 > this.max) {
           return false;
        } else {
           return true;
        }
      }
    </script>
    

    This does prevent the user from inserting a larger value by pasting.

    To prevent the user from deleting characters so that the value becomes too small, you would need to handle the rubout key, which is more problematic due to keyboard differences. But it would be poor usability. Suppose the user typed 30, then realized he meant to type 40. A code that prevents changing the value to too small would prevent removing either digit!

    Browsers are expected to have their own user interface for <input type=number>, and this is the reason for using it. The interface is not meant to prevent the user from typing too large values but to detect them and report them so that the user can correct them. Before trying to substantially modify this, consider the potential confusion. If you do add code that prevents out-of-ranfe values, browsers will not show diagnostic messages (e.g. “Number must be less than or equal to 50”), as they do by default if they support <input type=number>, so your JavaScript code should probably issue its own diagnostics.

    0 讨论(0)
  • 2021-01-06 02:21

    Have a read of the input element documentation.

    alternatively:

    Have a read of HTML5 Constraint Validation

    <input id="age" pattern="[0-9]" value="9" />
    <script>
        document.getElementById('age').validity.patternMismatch;
    </script>
    

    And then take a read of Regex numeric range matching

    0 讨论(0)
  • 2021-01-06 02:24

    Try this:

    var max = 100;
    $('input').keyup(function(){
    
    var inputValue = $(this).val();
    if(inputValue > max){
        alert('greater!');
    
        $(this).val('')
    }
    

    })

    here is jsfiddle: http://jsfiddle.net/h07Lc0Ld/1/

    0 讨论(0)
提交回复
热议问题