What html5 form attribute should be used for a zipcode? - html

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

You can try this
<Label>ZIP Code</Label><input type="text" pattern="[0-9]{5}" title="Five digit zip code" />

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

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.

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

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!

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

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/

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

Related

How to improve browser autocomplete suggestions without turning them off?

There are ten gazillion threads on here re. how to disable browser autocomplete behavior, e.g. How do you disable browser Autocomplete on web form field / input tag?. I do not want to set autocomplete="off" for my form fields. As the MDN documentation for how to do that states:
It is important to know that if you turn off autocomplete, you are breaking [WCAG rule 1.3.5]
So as an alternative to disabling autocomplete, I want to understand whether as a developer I can help the browser make its suggestions for my form fields more relevant.
As it is, I can see why many developers (or their bosses/clients) do end up wanting to be rid of the feature entirely. For example, when I added an <input name="title"> to a completely unrelated website I was developing locally, my browser suddenly started offering me a random sampling of questions I'd asked/edited across several StackExchange sites over several years:
How can I help the browser improve the user experience here? What factors do browsers use when choosing what text to suggest?
clearly the domain is not taken into consideration, unless my testing via localhost is triggering more promiscuous autocomplete than normal?
apparently at least one browser considers the field's name attribute to have universal semantic meaning, since Chrome is suggesting content I typed into other sites which happened to also use name="title" within their forms.
does any metadata on the form itself affect the suggestions? E.g. if I wrapped this input in a <form id="my-particular-form-has-nothing-to-do-with-qa-sites-btw"> might some browsers scope their autocomplete to only suggest previous name="title" entries into my-particular-form…?
Again, I am not looking for answers that tell me how to disable autocomplete or complaints that this is a duplicate of questions asking how to do that. I am happy to let the browser help the user fill in my form fields, but I want to help that help be more…helpful.
(Or, do I misunderstand the purpose of autocomplete to begin with? Is it only intended to be used for use cases like login credentials, shipping addresses, credit card number, etc. and I should be using autocomplete="off" for everything else?)
Current Auto Complete Behaviour is a mess!
Browser use various methods to determine if a field should be auto-complete.
For example the typical username, password combo a browser will look for two fields, one of which is type email and the other type password.
They also look at the name attribute as well as the type attribute to further try and determine whether a field should be auto-completed.
Finally depending on the browser they also look for fields that they expect to see together and use associated labels to work out what fields are which (which is why it is important to properly link labels with form fields!).
A prime example of this would be credit cards where they would expect to see cardholder name, credit card number, expiry etc.
Without at least 2 of these items auto-complete won't work (yet again depends on which browser you use).
Because each browser has a unique way of implementing this feature it is sometimes difficult to prevent 'cross site contamination' of results.
Domain is not a consideration as you already suspected.
However there are a couple of things you can do:-
The 'old' way (current way)
Give the input an unusual name attribute (i.e. name="xA123IIasd") .
As this is one of the primary factors in determining what a field is for (as far as a browser is concerned) and does not interfere with the user experience in any way it is a great option.
It won't work on username and password fields though as browsers have optimised for that. It also doesn't guarantee success but it will improve 'cross site contamination' for most fields.
You may also want to try giving the field a slightly different label than standard, as long as it doesn't impact usability (i.e. "Your First Name" instead of "First Name").
The new (better) way [not fully supported]
Use the new autocomplete options, part of the latest 'living standard'.
Support is unclear (i.e. can't find these on caniuse.com, only 'off') but I know it works in Google Chrome and Opera, kinda works in Safari (some items supported, some not), it is better than nothing!
Here is a list of the full 53 options you can use.
By adding these to your inputs you can control what the browser will expose as options for autocomplete.
For every other browser, choice is yours, browser sniff and switch autocomplete off or just leave it as it is 'expected behaviour' (even if it is not a great experience).
One more interesting feature
One final feature that the new autocomplete has is 'sections'.
This allows you to 'scope' the auto complete to a particular set of fields.
For example:-
<fieldset>
<legend>Package One Ship To</legend>
<label> Address: <textarea name="pack1Add1" autocomplete="section-packageone shipping street-address"></textarea> </label>
<label> City: <input name="pack1Add2" autocomplete="section-packageone shipping address-level2"> </label>
<label> Post Code: <input name="pack1Postcode" autocomplete="section-packageone shipping postal-code"> </label>
</fieldset>
<fieldset>
<legend>Package Two Ship To:</legend>
<label> Address: <textarea name="pack2Add1" autocomplete="section-packagetwo shipping street-address"></textarea> </label>
<label> City: <input name="pack2Add2" autocomplete="section-packagetwo shipping address-level2"> </label>
<label> Postal Code: <input name="pack2Postcode" autocomplete="section-packagetwo shipping postal-code"> </label>
</fieldset>
This means you can use auto complete twice on one page as each group is treated seperately from the other groups!
You will also note I use 'shipping' within the auto-complete to dictate to use the shipping address, the other option here is 'billing' (those are the only two options for address types at time of writing).

What is the correct input type for credit card numbers?

TLDR: Which input type can utilize the mobile numeric keyboards AND implement masking with spaces injected and a max limit for CVV and Credit Card inputs, such as: XXXX XXXX XXXX XXXX
When building forms, I have seen a varied degree of consistency surrounding the correct input type for credit cards. Here are my discovered pros and cons for each:
type=text
Able to mask easily with various libraries such as cleave.js or set maxLength attribute
Mobile users do not receive numeric-only keyboard, unless setting range to [0-9] (Only iOS users will get this experience, leaving Android users with full keyboard)
type=number
Proper keyboard shown on iOS and Android but unwanted characters can be entered and no maxLength can be set. Min and Max do not limit users from inputting more than 16 characters but do provide error messages when over the max. *Note, this input type is basically ruled out due to leading 0's being deleted. (Unacceptable for CVV's)
type=tel
Able to properly mask and is utilized all over the place, BUT may have unknown impacts on accessibility programs and autofillers. If anyone can provide clarification on the potential side effects of using this input type, that would be awesome!
These are all the types that came to mind. If anyone has any other recommendations, please let me know!
HTML
If you're trying to do this strictly with HTML, I believe the following is going to get you about as close as is currently possible:
<label for="ccn">Credit Card Number:</label>
<input id="ccn" type="tel" inputmode="numeric" pattern="[0-9\s]{13,19}" autocomplete="cc-number" maxlength="19" placeholder="xxxx xxxx xxxx xxxx">
inputmode sets the keyboard type (in this case, numeric)
pattern enables validation (in this case, numbers and spaces with a length of between 13 and 19) and it helps with keyboard type for browsers that don't yet support inputmode
autocomplete tells browser what should be autocompleted (in this case, a credit card number)
maxLength prevents the user from entering more than the set number of characters (in this case, 19, to include numbers and spaces)
placeholder gives the user an example (formatting hint)
JavaScript
For a more robust solution, JavaScript is going to be required. And rather than roll your own solution, it'd probably be best to use a battle-tested library. Cleave.js (as you mentioned) is a popular choice.
I’ve seen using type="tel" on many places, for the reasons you mention.
I would not recommend type="number" as then you have to fiddle with in/decrement arrows etc. And from certain point of view it is not a “number” in terms of what we usualy do with numbers (maths), see this comment on CSS tricks forum.
Another trick how to force numeric keyboard is using pattern="[0-9]*". This should work on iOS only. To make it work on Android as well, you have to combine it with the type="tel".
There's an attribute inputmode that's designed for that, it's not implemented yet (actually deprecated in HTML 5.2), but there's work done on it (FF/Chrome).
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
And see this discussion:
https://github.com/whatwg/html/issues/3290
For now set the autocomplete attribute to the correct value:
https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill
or implement a customized input with mask like you're using now.

input type="number" with currency formatting (thousands delimiters)

This has already been asked numerously and lots of examples have been provided, either with tons of JavaScript, or using the inputmode or the pattern attribute with some regex. However, none of these seem to work together with the numeric keyboard (at least not on my iPhone).
Therefore my question: is this impossible? (in plain and simple HTML5)
I need an <input> for currency with on-the-fly formatting, to edit numbers like this: 1,000,000.00 or, when changing the country, to 1 234 567,89 AND the numeric keyboard appears (important for mobiles). Notice the thousands separators.
Only HTML5 will not work today. (6-6-2016)
What you want is this:
<input type="text" pattern="your-pattern" inputmode="numeric">
However, inputmode is not supported in any browser yet.
The code above explained:
We can't use type="number" because the pattern attribute is not supported on that type, so we use type="text". A better choice might be type="tel" because it's also concerned with numbers and delimiters. However, I don't know the semantic implications of this (on SEO and screenreaders for instances). The safest approach is text
inputmode is new and allows you to specify what kind of input mode is required. Especially useful for mobile devices, as you can imagine
Considering you want to have on the fly conversion from one standard notation to another, you will have to use JavaScript so you can use it for your pattern validation if you really want to use a number type. Or maybe there is even another public API to control the keyboard through JS (but I doubt it, may cause security issues).
Finally, as always: if your validation is important, do it server-side. The client-side should never be trusted. (Even if they have cookies.)

HTML5 Input Types & Touch Device Keyboards: Appropriate Number, Tel & Text Usage?

I would like to automatically initiate the numeric keyboard on touch devices for zip code and social security number input fields. Zip codes are entered in a five digit format, while SSNs are entered as 111-22-3333. My understanding is that type=number and type=tel fields will automatically initiate the appropriate keyboard, so these inputs seem appropriate, but I'm not confident they are the right choice.
Type=Number
I originally thought type=number would be the optimal solution (since it sounds semantically correct), but have since found that this type is really only for true numbers and not strings of numeric characters. I've seen blog posts making accusations of browsers automatically including the comma as a thousands separator, and stripping leading zeros on submission (neither of which are zip/ssn friendly).
Type=Tel
From what I have read, this seems like the best solution to my problem. I'm concerned by the meaning of this new type though. Should I really be using a telephone field for zip code and ssn? What if some mobile phone manufacturer decides to start showing the address book for tel fields? That would make no sense for a zip or ssn.
Alternatives
I've found that the new pattern attribute of type=text inputs can be used to trigger the numeric keyboard on iOS devices, but that only partially solves the problem.
I've also found a new attribute inputMode which seems to be the ideal solution, but doesn't seem to be implemented by any browsers yet.
The Question
What I'm hoping is that someone has a suggestion or a best practice? Should I use TEL? Should I go with the iOS solution and ignore other devices? Will inputMode ever work?
My suggestion is to use pattern and inputMode only.
Additionally, Type = number is acceptable if you are only accepting integers between 0-999 and you are okay with the extra validation that will be done - even if the user clicks cancel.
Type=Number has issues even if it is a number, let alone a SSN etc, as it has unpredictable handling of values with regard to negative numbers, localization, precision, leading zeroes, etc, depending on the browser's implementation. Best practice is to avoid unless you have an internal website with a fixed user base where you know the devices/locales being used - unless you are expecting an integer between 0 and 999. Negative numbers, decimals, and thousand characters all will have problems on certain devices.
In addition, if you use 'type' the page will validate data even if the user clicks a cancel button. You could globally turn off validation, but now the page will auto-delete any invalid data on post back! If either of these are acceptable to you, you can use 'type'.
Type=Tel works 'today' but as you point out, it is dangerous to use as who knows what browsers will do in the future. Not to mention that '122-222-2223 Ext.34' isn't even accepted by these devices. I would advise caution if it is a phone number, and avoidance otherwise. The day may come that some device decides to validate the number even though the HTML5 specs say not to.
Pattern=... is good to add. Most browsers will ignore it, so use another validator as well, but at least newer iOS devices will use it, and that's 45% of mobile users.
InputMode=... seems to be the only other hope at this time. Hopefully it will get supported in the future.

Can I add HTML5 elements to existing HTML documents?

So I have an existing HTML page that has a field for Last 4 digits of Credit Card:
<input value="" name="Last4ofCC" maxlength="4" id="Last4ofCC1">
Works great, but a feature request just came in to make it a numeric field and not allow non-numeric characters.
At first I thought of plugging in some Javascript, but then I thought, why not just use an HTML5 element. I changed to the following:
<input type="number" value="" name="Last4ofCC" max="4" id="Last4ofCC1">
But not only does it still allow non-numeric characters, the max attribute doesn't work either! I'm testing this on FireFox 8, so not sure what the problem is.
Does anyone know what I've done wrong here?
you need to include the proper doctype at the top of your page in addition to changing your input types.
<!DOCTYPE html>
However, it's not going to do what you think it's going to. Setting an input as a type="number" will pretty much only get you the spinners on the side and tell the form what it should be. If you want to ensure only digits are entered, you will need to do a regex, like /^\d+$/ on keyup.
More info on HTML5
Yes, you can add HTML5 features to existing pages. Browser support to them is, at least at present, independent of any doctype stuff you may or may not have at the start of your page.
It is, however, probably not a good idea to use type="number" for reading four digits. It is meant for reading numeric data, and it will happily accept 42 without requiring any more digits, for example. Moreover, the user interface may even confuse the user. But if you use type="number", you should in this case set min="0" and max="9999".
A better HTML5 construct is pattern="[0-9]{4}" required. It is supposed to run a check on the input, checking that it consists of exactly four digits. This is supposed to happen even when JavaScript is disabled.
Since browser support is still rather limited, it’s a good idea to use JavaScript checks, too, as a convenience to the user.
'max' indicates the maximum value allowed, not the maximum number of characters.
Jason's answer is mostly correct. However, you should not do validation on keyup unless the user needs additional help. I'm the author of h5Validate. In the process of improving conversion rates in a large production shopping cart, we discovered that users get confused if they see a validation error message while they're still trying to type the number.
h5Validate first runs validation on change, and if the value is invalid, it will add keyup to help the user correct the field with each keystroke. This seems like a minor nitpick, but the difference it makes measures in the millions of dollars per year in revenue for large scale shopping cart systems.
Nothing, as far as I know Firefox doesn't support those yet, http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML5%29. Try Chrome to see the effect.
You can check out the latest form support for Firefox here (it's supposed to be support):
https://developer.mozilla.org/en/HTML/Forms_in_HTML
Also check out:
http://caniuse.com/#search=form%20validation
This jQuery plugin will add support for all browsers though. It's a safe approach that still uses HTML5 syntax:
http://ericleads.com/h5validate/
Good luck!