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

You could use Regex to completely prevent the user from entering in any letters into the input field.

So on your input element I would add the following event listener: onkeypress="preventNonNumericalInput(event)"

<input class="small-input " pattern="[0-9]*" value="" type="number" onkeypress="preventNonNumericalInput(event)">

And then in your JavaScript file you'd create the following function:

function preventNonNumericalInput(e) {
  e = e || window.event;
  var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
  var charStr = String.fromCharCode(charCode);

  if (!charStr.match(/^[0-9]+$/))
    e.preventDefault();
}

I've tested this and it should prevent any non numerical input and any special characters eg @#./? etc...


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, as explained above.

Link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number

You should use Javascript instead, following this link.


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>

Tags:

Html

Css