What html5 form attribute should be used for a zipcode?

前端 未结 8 2017
我寻月下人不归
我寻月下人不归 2021-02-01 02:51

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

相关标签:
8条回答
  • 2021-02-01 03:12

    You can try this

    <Label>ZIP Code</Label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />
    
    0 讨论(0)
  • 2021-02-01 03:14

    There are various options from my POV, but I think the best is already given by Md Johorul Islam: the pattern attribute.

    The options:

    • Use a regular expression (the pattern attribute);
    • Use a custom (jQuery) mask control, like jQuery mask;
    • For the platforms where this is not supported, use type=text with a maxlength.

    Note: Despite these options: always validate server side!

    0 讨论(0)
  • 2021-02-01 03:18

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

    0 讨论(0)
  • 2021-02-01 03:24

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

    0 讨论(0)
  • 2021-02-01 03:26

    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

    0 讨论(0)
  • 2021-02-01 03:29

    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/

    0 讨论(0)
提交回复
热议问题