How to use webform's "number" element appropriately

Tuesday, December 20, 2022
by Kevin Paxman

Webforms has a "number" element that you can use, but did you know that it shouldn't be used for all cases where you want people to enter a number? (Hat tip to this GOV.UK article.)

In most browsers, the number element has arrow buttons that allow you to increment and decrement the entered number. You can also change the number using the up and down arrow keys.

a sample number field

These affordances, along with an issue where browsers won't properly increment or decrement the number if it has too many digits, mean that the number element should only be used in limited use cases, where the number will never be too long, and it makes sense to be able to scroll through numbers.

For example, a "quantity" field is a good use case for the number element - you might reasonably expect a visitor to increase or decrease the quantities using the arrows.

On the other hand, a "product ID number' field should be a regular text field, because it might be a longer number, it doesn't really make sense that you'd want to enter it by scrolling through the digits, and then there is the additional issue that a number element will not preserve leading zeroes when incrementing/decrementing.

The keyboard that appears on an iPhone when a number field is clicked

On an iPhone, the keyboard that appears when a number field is clicked allows for additional characters besides numbers.

The keyboard that appears on an iPhone when a text field with the number pattern is clicked

On an iPhone, the keyboard that appears when a text field is clicked, when the field has been set to use the pattern for numbers, allows only numbers.

One final thing you may want to consider when selecting what type of field to use is the keyboard affordances that phone browsers use when the field is selected.

On an iPhone, the keyboard that appears when a number field is clicked does default to include the number keys, but it allows for additional characters besides numbers.

If you use a text field, by default you will see the full keyboard, but you can set the field to use the pattern [0-9]*, and then you will get a keyboard that allows only numbers.

When using this pattern, it is usually a good idea to add a custom message that will be shown to "real" keyboard users if they enter invalid characters and try to submit the form.

a screenshot of form validation showing the [0-9]* regular expression and a custom pattern message

Unfortunately, webforms do not support adding this pattern validation to the number field - technically, it violates the specification, even though Apple uses it to determine which keyboard to show. Perhaps someday webforms will support the "inputmode" attribute, another way to determine keyboards.