Is it best to use a \'text\' attribute with a limit on the number of characters, or can I use a number attribute in an input for a zipcode.
Just trying to get my head ar
You can try this
<Label>ZIP Code</Label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />
There are various options from my POV, but I think the best is already given by Md Johorul Islam: the pattern
attribute.
The options:
attribute
);type=text
with a maxlength
.Note: Despite these options: always validate server side!
<input type="tel" pattern="[0-9]*" placeholder="Zip Code" max="99999" />
Type set tel
to show numeric keypad, pattern to except values 0-9 and max set to prevent values beyond US 7 digit zip codes.
"Best" is subjective/contextual. But from a usability perspective, Zach Leatherman studied number-ish inputs in 2016 and specifically addressed the ZIP input.
The goal was to make "big number keyboards" appear on mobile devices. This may seem insignificant, but easing form input in e-commerce checkout forms is an important goal.
It seems that some day the inputmode="numeric"
attribute will be appropriate for zip inputs. But for now, only Chrome/Android supports it (Firefox has it behind a flag).
Zach developed a small library called numeric-input as part of his formcore package which will implement the best possible case for whatever browser is being used.
Keep in mind, the library is a couple years old, and browser behavior might have changed since then.
If you have any international users you are going to want to allow alpha numeric via type="text"
Example: UK postal codes are formatted as AA9A 9AA
9 = any number
A = any letter
You can use either and the form will work. However, it might be a better idea to use number because, for example, mobile devices would invoke a different keyboard layout - with numbers and helper characters instead of the full alphanum keyboard.
But, if you think setting one type as opposed to another will offer a higher level of security, you're wrong. No matter which type you put, it will offer you no security. Every form input needs to be checked on the server as well - that's where the real security check happens. The check that you do in browser, is more of a UI/UX thing.
Here is a nice article about different input types: http://html5doctor.com/html5-forms-input-types/