Use <input type="number"> for numeric form fields

Posted . Visible to the public. Repeats.

Any form fields where users enter numbers should be an <input type="number">.

Numeric inputs have several benefits over <input type="text">:

  • On mobile or tablet devices, number fields show a special virtual keyboard that shows mostly digit buttons.
  • Decimal values will be formatted using the user's language settings.
    For example, German users will see 1,23 for <input type="number" value="1.23">.
  • Values in the JavaScript API or when submitting forms to the server will always use a point as decimal separator (i.e. "1.23" even when the browser displays 1,23).
    You don't need any "conversion" hacks which try to replace commas with dots.
  • Additionally, tests which control browsers with Selenium will also see point-formatted values on non-English locales.
    Example: expect(page).to have_field("Example", with: "1.23") in Ruby with Capybara will work even on German systems where the browser displays 1,23 in the input field.

All in all, numeric inputs are great and you should use them.
However, they come with some quirks that you may want to avoid. We have a separate card for that.

Note

If you cannot use type="number", you can use the inputmode Show archive.org snapshot HTML attribute to control the virtual keyboard's appearance on mobile/tablet devices.
There is also the pattern Show archive.org snapshot attribute which allows specifying valid characters; it affects an input's validity state and will not prevent entering invalid characters.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2024-02-05 16:41)