What html5 form attribute should be used for a zipcode?

前端 未结 8 2018
我寻月下人不归
我寻月下人不归 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:30

    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.

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

    “Should” is a strong word, but there is actually a “should” class statement about issues like this. HTML5 CR says about input type=number:

    Note: The type=number state is not appropriate for input that happens to only consist of numbers but isn't strictly speaking a number. For example, it would be inappropriate for credit card numbers or US postal codes. A simple way of determining whether to use type=number is to consider whether it would make sense for the input control to have a spinbox interface (e.g. with "up" and "down" arrows).

    The means that the only feasible element for the purpose is input type=text, when using built-in constructs. You can use the maxlength attribute to set the maximum number of characters (works on all browsers) and additionally a pattern attribute what specifies the allowed characters and combinations, too; its value naturally depends on the zipcode type(s) to be used. For international postal addresses, you probably should not use any pattern or even maxlength, since the formats vary.

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