input type="number" be a 3 digit number or a 8 digit number

Viewed 3749

Is it possible to limit the number of digits that a user can into a field. E.g.

  • For a 3 digit number 184 only
  • For a 8 digit number 18875264 only
2 Answers

HTML5 introduced a new attribute for input tag - pattern. You can specify the regex as value of pattern attribute to validate the input.

pattern does not work with type="number" so I'll use type="text" instead. type="tel" will also work but don't use it unless you really want to input a telephone number.

<form>
  <label for="num-input">3 or 8 digit number: </label>
  <input id="num-input" 
         type="text"
         required
         pattern="\d{3}|\d{8}" 
         title="must be 3 or 8 digit"/>
  <br/>
  <input type="submit" value="submit" />
</form>

The regex \d{3}|\d{8} matches 3 digit number or 8 digit number.

The most basic HTML-only way of limiting it to three digits would be:

<input type="number" max="999" min="-999" />

However, this won't force the max or min attributes when the user inputs a value by hand instead of using the add or substract buttons of the input. To validate that, you'd need to add some javascript that checks the users input:

document.querySelector('input[max], input[min]').onblur = function (event) {
  const numValue = Number(event.target.value);
  // if within the expected range, do nothing
  if (numValue  < event.target.max && numValue  > event.target.min) return;
  // check if it's closer to max than to min,
  // then set the value to max or min accordingly
  event.target.value = event.target.max - numValue  < event.target.min - numValue  ?
    event.target.max :
    event.target.min;
}

Update

Upon further inspection, I realized I had misunderstood the question.

In order to allow only three or eight digit numbers, you could use the following validation:

document.querySelector('input').onblur = function (event) {
  let valString = Number(event.target.value).toString();
  if (valString.length === 3 || valString.length === 8) return;
  event.target.value = valString.length > 8 ?
    valString.substr(0, 8) :
    (valString.length > 3 ? valString.substr(0, 3) : null);
}
<input type="number" />

This will trim any value longer than eight digits to eight, trim any value longer than 3 but shorter than eight digits to three, and leave blank if 1 or 2 digit values are inputted.

Related