2

What pattern should i use to accept number range such as 100 - 200?

<input type="text" pattern="" name="numRange">

Also if it is possible to make sure the min is lower than max. i.e 100 - 200 here 100 should be lower than 200. Thanks!

kofhearts
  • 3,607
  • 8
  • 46
  • 79

1 Answers1

4

As mentioned by revo in the comments you could validate a number range like so:

<form action="somefile.php">
  <input type="number" step="1" min="100" max="200" id="numRange">
</form>

Regex Method (less recommended):

var input = document.getElementById('numRange');

input.oninvalid = function(event) {
  event.target.setCustomValidity('number range should be betweeb 100-200')
}
<form action="somefile.php">
  <input type="text" name="number" placeholder="100-200" pattern="^(1\d\d|200)$" id="numRange">
</form>

The main difference between the two methods is the first uses type="number", and the second relies regex, javascript and uses type="text").

l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • 1
    That's right. You could also shorten the regex to `(1\d\d|200)`. Ends anchors are applied by default: `pattern="(1\d\d|200)"`. – revo Jun 17 '18 at 08:59