Read more

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

Arne Hartherz
February 05, 2024Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2024-02-05 17:41)