What html5 form attribute should be used for a zip

2020-05-19 23:36发布

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 around all the different attributes with the forms in html5. Cheers

8条回答
爷、活的狠高调
2楼-- · 2020-05-19 23:58

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

查看更多
甜甜的少女心
3楼-- · 2020-05-20 00:00

To allow ZIP+4:

<input type="text" placeholder="Zip Code" title="Please enter a Zip Code" pattern="^\s*?\d{5}(?:[-\s]\d{4})?\s*?$">

To be friendly to the user, this also permits whitespace before/after the string, which the developer will need to trim serverside.

查看更多
狗以群分
4楼-- · 2020-05-20 00:06

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/

查看更多
再贱就再见
5楼-- · 2020-05-20 00:07

You can try this

<Label>ZIP Code</Label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />
查看更多
Summer. ? 凉城
6楼-- · 2020-05-20 00:10

<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.

查看更多
戒情不戒烟
7楼-- · 2020-05-20 00:14

"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.

查看更多
登录 后发表回答