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-20 00:18

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

查看更多
叼着烟拽天下
3楼-- · 2020-05-20 00:20

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!

查看更多
登录 后发表回答