Numeric Validation
Numeric Inputs
Numbers are even easier to validate than text. For number input types, the HTML5 spec gives youattributes like min
, max
, and step
. Each of these do pretty much what you would expect.
min
and max
set the minimum and maximum values that the arrows in the input will allow. step
sets the increments for between possible values. There’s also value
, which sets the starting value of the input.
Of course, you’ll probably notice that users can still type whatever number they want into numeric inputs. If you want to really limit possible values, consider a range instead.
Range Inputs
The range input type creates a slider on the page. It also has min
, max
, step
and value
attributes. If you want to display the current value
of the range when it changes, you’ll need to use some JavaScript to pull the value from the range. Here's an example:
// grab <input id="range-example" type="range" min="0" max="5" step="1"> from the page var rangeInput = document.querySelector('input#range-example'); // grab <p id="output"></p> to display the output var output = document.querySelector('p#output'); // update the display when the range changes rangeInput.onchange = function() { output.innerHTML = this.value; };
<input type=number>
<input type=number min=100 max=999 step=5>