Search code examples
html

Input type="number" with pattern="[0-9]*" allows letters in firefox


The question is in the topic's title. Input type="number" with pattern="[0-9]*" works fine in Chrome, but allows letters in Firefox. Is there any way to fix it without using jQuery or JS?

.small-input {
    -moz-appearance: textfield;
}
.small-input::-webkit-inner-spin-button {
    display: none;
}

.small-input::-webkit-outer-spin-button,
.small-input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
<input class="small-input" pattern="[0-9]*" value="" type="number">


Solution

  • Seems that Firefox doesn't restrict you from entering alphabetic characters into a number input, however it still will validate the input upon submitting your form as seen below. Note that both e and E are valid in numeric inputs.

    Also, according to MDN,

    <input type="number"> elements do not support use of the pattern attribute for making entered values conform to a specific regex pattern. The rationale for this is that number inputs can't contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the min and max attributes

    So no need to use it.

    Selecting a numeric input really does two things. First on mobile devices is should bring up a numeric keypad instead of a normal keyboard to enter input, second it should only allow numbers as valid input. So if you want to prevent a user from entering text into one, you'll need JavaScript.

    You'll see by the example below that when you try and submit the form, if the input isn't numeric it will prompt you to correct it, and the pattern attribute is unnecesary:

    .small-input {
      -moz-appearance: textfield;
    }
    .small-input::-webkit-inner-spin-button {
      display: none;
    }
    .small-input::-webkit-outer-spin-button,
    .small-input::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
    }
    <form>
      <input class="small-input" value="" type="number">
      <button>Button</button>
    </form>