So, all question is in the topic's title. Input type="number"
with pattern="[0-9]*"
works fine in Chrome, but allows letters in FF. 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">
a " e " character or " E " character. optionally, a " - " character or " + " character.
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.
You can specify a minimum length, in characters, for the entered telephone number using the minlength attribute; similarly, use maxlength to set the maximum length of the entered telephone number.
The pattern attribute specifies a regular expression the form control's value should match. If a non- null value doesn't conform to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With