0

So I would like to create a form field where the user is only able to input numbers between 1-10, and I would like it to show an error upon submission if the user enters any number bigger than that.

I know I need to use the title tag for the error, and pattern tag for it however what expressions would I use for the pattern tag?

PinkieBarto
  • 19
  • 1
  • 6

4 Answers4

0

Use this

<input type="number" min="1" max="10"> with html5 min and max attributes you can restrict the value of some input fields like dates and numbers.

Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
0

You can use html5 validation by adding required attribute alongside with min and max:

<form action="">
  <input type="number" max="10" min="1" required />
  <button>submit</button>
</form>

The required attribute

Alex Char
  • 32,879
  • 9
  • 49
  • 70
0

This solution has a bit of JavaScript code, and works also with no HTML5 compliant browsers
(older and new one).

var widget = document.querySelector('input[name="onlyDigits"]');
widget.addEventListener('input', function() {
  this.value = this.value.replace(/\D/g, '');
});
<input type="text" name="onlyDigits" />
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
0

<form action="">
  Num 1-10:<br>
  <input type="number" step="1" min="1" max="10" required />
  <input type="submit">
</form>
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49