Html5 Number Inputs

It’s great to be able to have html5 do JavaScript input validation for you, but there were a few reasons we were hesitant to use them until now, which are now mostly fixed.

Differences between number and text inputs:

  1. The number keyboard will show on mobile instead of the letters keyboard
  2. A “spinner” will show at the right side of the input box, and you can click the up and down arrows to change the value
  3. If you type a letter or any other character that isn’t used in a number, the box will turn red, and you will not be able to submit the form
  4. Other validation helpers:
    1. You can specify a min and max value
    2. You can specify in what increment the number can change by tweaking the “step”. Decimals are not accepted by default.
    3. A regex pattern

I did not want the up and down errors to show in the box, because 1) I don’t think anybody uses them, and 2) Some inputs are two small to fit them.

I used this to hide it in Firefox:

input[type="number"] {
  -moz-appearance: textfield;

And the following to hide it in Chrome and Safari:

input::-webkit-inner-spin-button {
  -webkit-appearance: none;

I also had trouble with the red border not showing, because bootstrap had priority over the html5 validation. Bootstrap’s blue border showed on focus even when the input was invalid. I used the following css to make it red when it was invalid:

input[type="number"].form-control:invalid {
  -webkit-box-shadow: inset 0 1px 1px red, 0 0 8px red;
  box-shadow: inset 0 1px 1px red, 0 0 8px red;

Note that the above css does not work nicely with required inputs. In that case, the page loads with the cells already red.

Leave a Reply