The most common of elements can be more flexible than you think
Colour inputs <input type=”color” />
In forms where colour input is required, the ‘color’ type provides either a colour picker or a hexadecimal text input to provide a value. The display of the colour picker can vary depending on the browser, which may only supply a limited subset of colours by default. A site using this input should provide an alternative method of input in this case. A default colour can be applied by supplying a ‘value’ to the field, but this must be a valid hex colour and not a CSS colour name or function like ‘linear-gradient’. If an invalid colour is added, it will default to black.
Number inputs <input type=”number” min=”0” max=”99” />
When a form requires a number, it makes sense to use an input specialised for that purpose. A number field get automatic validation to be sure the value is numerical. Most modern browsers will also render stepper buttons, which allow the user to increment or decrement the value inline. On a touchscreen device, the keyboard will update to show numbers by default and may even allow users to swipe to increase and decrease the value. Extra attributes on the input can limit the value being entered. For example, an age field may have a ‘min’ attribute to stop a negative value being added.
<input type=”range” min=”0” max=”10” />
When a specific value is not necessary, a range input may be more useful. In this case, browsers can render a more appropriate slider to allow the user to select a value more easily. These are useful for simple components such as volume sliders.
Modes on any input
While these type inputs are great for their typical use case, it can become a hindrance for others. For example, a credit card number is numeric but does not need the increment and decrement behaviour that the ‘number’
type provides. <input inputmode=”numeric” pattern=”[0-9]*” />
Most forms would fall back to regular text input in this case and use a ‘pattern’ attribute to define what is required. This requires the developer to know the right pattern for their input, which can cause a similar issue to before. An ‘inputmode’ attribute is coming to browsers that aims to tackle this issue. It hints to the browser what kind of interface would help the user add data to this field. Having a value of none will ensure no virtual keyboard is displayed, allowing for a custom keyboard within the page itself.
Always server validate
As great as these input types are, they are not without flaws. Browsers may not support a specific type or can have unexpected valid inputs, such as ‘e’ for number inputs. At the very least, a user can still edit the HTML on a page and remove validation altogether. It is important that any data submitted to a server is also validated on that side to avoid any issues. Include client-side validation to help.