0

I have an input text form where it's required to insert a value from 1 to 10.

I tried to put a mask to customize it but it makes me write values over 10, how do I set the only possible values to be from 1 to 10 and not less or more?

The form input type="text" name="level" id="level"

The mask I used to make it accept only numbers and to make it 2 digits long

function maskFormatterForLvl(val) {
$(val).mask("ZZ", {
    translation: {
        'Z': {
            pattern: /[0-9]/,
            optional: true
        }
    }
});

};

I tried with the "max" attribute but it didn't work, probably because I'm new to JavaScript

Anchit Jain
  • 181
  • 2
  • 14

3 Answers3

2

If your input field values are numbers, then you can use input type 'number' . The min and max attributes represents number range to input. Hope this is much simpler.

<input type="number" min="0" max="10">

UPDATE

Inorder to hide the arrows you could use the following.

/* Webkit browsers like Safari and Chrome */
    input[type=number]::-webkit-inner-spin-button, 
    input[type=number]::-webkit-outer-spin-button { 
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        margin: 0; 
    }
/* For Firefox */
    input[type='number'] {
       -moz-appearance:textfield;
    }
melvin
  • 2,571
  • 1
  • 14
  • 37
0

You can use this regex if you have to use type="text"

<input type="text" pattern="([0-9])|(10)">
Crackers
  • 1,097
  • 6
  • 14
0

You can use a text input and allow only numbers to be typed in, with the use of charCode . From 48 to 57 are the keyboard numbers from 0-9.

If it passes this validation then you check if it exceedes the max value of your input.

For the min value, the user cannot enter something below 0 because to do that he should be able to write -, which doesn't pass the first condition ( numbers only )

const input = document.getElementById('level')
input.onkeypress =  function(e) {
    var ev = e || window.event;
    if (ev.charCode < 48 || ev.charCode > 57) {
      return false;
    } else if (this.value * 10 + ev.charCode - 48 > this.max) {

      return false;
      } else if (this.value * 10 + ev.charCode - 48 < this.min) {

      return false;
    } else {
      return true;
    }
  }
<input type="text" name="level" id="level" min="1" max="10" maxlength="2">
Mihai T
  • 17,254
  • 2
  • 23
  • 32