Browser automatically validates a non-mandatory field with an empty value - html

I have a simple form which contains an <input> intended for filling in email addresses should the user decide to do so, i.e. the field is not mandatory. I also use the type="email" attribute as it helps with autocompletion as well as it particularly benefits smartphone users - it causes their keyboards to rearrange in order to facilitate email input.
However, there are also users with not as advanced mobile devices who may have some difficulties with typing the # sign. Also, there still exist some desktop users who cannot type it either; I know some personally and I presume that there are many more. For these users I set the initial value of the <input> to #. I shall stress that this is not a placeholder.
But now these two things clash. The browsers' native form validation mechanisms activated by the type="email" now prevent form submission since they do not understand that the field is not mandatory and that I do not mind users sending the # as the value.
Is there some way to tell the browser to validate the field only if the value is not # or empty string? Obviously, it would be really easy to make my own validator using javascript but I would not like to resort to that.
Or is my premise about users unable to type the # sign false and I could solve this issue by simply leaving the <input> empty in the first place? Is there any research on this matter? I still occasionally see relatively recent complaints by desperate users on various tech forums and I imagine that the vast majority of similar inexperienced users does not go ask online, perhaps because they do not even know how to.
Or should I use the good old type="text"?
How do you think I should approach this?
Thank you in advance!

It seems the only way to disable User agent validation is to add a novalidate to your form. Obviously this would disable all UA validation on the form and not just the one input. Maybe you could use Javascript validation for all your other inputs and use input[type="text"] for everything else.
<form novalidate>
<input type="email" value="#">
<input type="submit" value="submit">
</form>
I would use javascript to alter the field depending on the user agent.
Its a real shame that the W3C didn't think of this, surely a simple novalidate on the input would suffice, I really hope this gets fixed, otherwise all input[type="*"] are kind of useless for future use.

Related

Disable the browser autofill on input fields (All browsers)

I have a simple html form, i am using "google autofill" on a field that autofill data on two fields.
The issue is that the browser address autofill is overlapping the google autofill.
How to disable the browser autofill on fields on every browser ?
Feel free to share thoughts on this.
Thankyou.
Here's the universal solution that will work in all browsers as of May 2021!
TL;DR
Rename your input field names and field ids to something non-related like 'data_input_field_1'. Then add the ‌ character into the middle of your labels. This is a non-printing character, so you won't see it, but it tricks the browser into not recognizing the field as one needing auto-completing, thus no built-in auto-complete widget is shown!
The Details
Almost all browsers use a combination of the field's name, id, placeholder, and label to determine if the field belongs to a group of address fields that could benefit from auto-completion. So if you have a field like <input type="text" id="address" name="street_address"> pretty much all browsers will interpret the field as being an address field. As such the browser will display its built-in auto-completion widget. The dream would be that using the attribute autocomplete="off" would work, unfortunately, most browsers nowadays don't obey the request.
So we need to use some trickery to get the browsers to not display the built-in autocomplete widget. The way we will do that is by fooling the browser into believing that the field is not an address field at all.
Start by renaming the id and the name attributes to something that won't give away that you're dealing with address-related data. So rather than using <input type="text" id="city-input" name="city">, use something like this instead <input type="text" id="input-field-3" name="data_input_field_3">. The browser doesn't know what data_input_field_3 represents. But you do.
If possible, don't use placeholder text as most browsers will also take that into account. If you have to use placeholder text, then you'll have to get creative and make sure you're not using any words relating to the address parameter itself (like City). Using something like Enter location can do the trick.
The final parameter is the label attached to the field. However, if you're like me, you probably want to keep the label intact and display recognizable fields to your users like "Address", "City", "State", "Country". Well, great news: YOU CAN! The best way to achieve that is to insert a Zero-Width Non-Joiner Character ‌ as the second character in the label. So replacing <label>City</label> with <label>C‌ity</label>. This is a non-printing character, so your users will see City, but the browser will be tricked into seeing C ity and not recognize the field!
Mission accomplished! If all went well, the browser should not display the built-in address auto-completion widget on those fields anymore!
Hope this helps you in your endeavors!
This is not so easy to implement cross-browser.
Many browsers, in particular Google Chrome has pushed very hard on having a tool that helps users auto-fill their forms, but for developers this has been just been painful.
I could list tons of different ways that could or could not work depending on different factors, but I will post this one solution that finally does the trick. So if you have been looking for this answer all over the internet, leave me a comment below and tell me if it worked.
First of all, due to browser compatibility, we need to add these attributes as eventually things will work properly:
autocorrect="off" spellcheck="false" autocomplete="off"
This is supposed to be enough, BUT IT IS NOT! and we all know that. so the next thing to do is to add a little bit of JS in case the browser managed to ignore these attributes. For this example I will just use jQuery and assume that we are dealing here with inputs, but you can chose any selector you want.
$('form').attr('autocomplete', 'off');
$('input').attr('autocomplete', 'off');
Finally, this will work 50% of the times, but if the browser has previously detected that this form was filled up in the past it might judt ignore it, so let's add a final step.
There is another popular trick that involves adding a dummy password field, but I don't like adding dummy content, and I don't find this solution elegant so I will just skip it, besides it doesn't work.
To be honest this final step is the one that makes everything work, but as I said it is better if our attributes are ready for future compatibility. Keep in mind that the browser will never attempt to autocomplete a readonly input, so for this last step we need to make it readonly and on focus bring it back to normal, so add the following JS in the onfocus attribute:
readonly onfocus="this.removeAttribute('readonly');"
BINGO! it should work now.
So the final input looks like this:
<input type="text" name="email" required autocorrect="off" spellcheck="false" autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" />
<script>
$('input').attr('autocomplete', 'off');
</script>
It seems like a lot, but this works 100% of the times. as I said probably with readonly onfocus="this.removeAttribute('readonly'); is enough, but browser compatibility is changing and eventually things will work properly, so it is good to have it there.
If this worked (or did not work) leave a comment!
Thanks

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

How to stop Chrome from autocompleting text areas?

I am dealing with a text area in part of a contact form that Chrome wants to autofill with the user's address. As a result many contact requests are submitted by users with their address in the comment field. Besides the obvious potential security issues that could be exploited, my concern is that from a user's standpoint we're providing a contact form without an area to type a message. And from a support standpoint, we're having to ask users to send us another message with their actual question.
HTML:
<textarea id="element_10" class="validate[required] floatlabel js-auto-size multiple-lines" name="element_10" placeholder="Message*" rows="10" cols="60" required autocomplete="off"></textarea>
Answering my own question since I did not find the answer on Stack or in any Chrome browser docs.
In some cases, the browser will keep suggesting autocompletion values
even if the autocomplete attribute is set to off. This unexpected
behavior can be quite puzzling for developers. The trick to really
forcing the no-autocompletion is to assign a random string to the
attribute, for example:
autocomplete="nope"
Since this random value is not a valid one, the browser will give up.
https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
I tried all the suggestions and nothing really worked consistently.
If I set one input to autocomplete="nope" it works.
If I set two or more it breaks them all.
If I set two to autocomplete="nope" and autocomplete="no" it works on those two but breaks again if I do anything to a 3rd.
My form only has 3 inputs. I just set email and phone and left name alone. That pretty much solves my problem.
I have some jquery validation that pretty much does not work with autocomplete and this client really does not want to be bothered with junk emails.
Also Chrome treats a one row textarea exactly the same as a input.

Is it good practice to give html elements id attributes that are only to be used for testing purposes?

Suppose I have a form like so:
<form action="/foo" method="POST">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="Login">
</form>
In my case, there is no need for me to give any of the input tags an "id" attribute. It isn't styled via CSS, there is no javascript referencing it, etc... However, there is a QA department that would love it if it had a hardcoded "id" such as "login-button" so that their automated test would stay stable.
CONS As the developer a am highly skeptical about adding id attributes that serve no functional purpose.
I think it clutters the code.
Confuses future developers looking at
it.
Binds us to whatever testing tool is being used at the time.
Binds us to code outside of the product's codebase.
Starts down a slippery slope of the code knowing something about how it will be tested and vice-versa.
PROS:
From the QA perspective, I can certainly sympathize that this would:
make their work easier.
provide stability (in the short term)
Can I get some help expanding on the Pros/Cons lists I have started here?
One important functional reason to include id attributes on form inputs is so that you can explicitly associate the corresponding label elements with the inputs:
<form action="/foo" method="POST">
<label for="username">User Name</label>
<input type="text" id="username" name="username">
</form>
This is important for accessibility and usability. Screen reader users rely on this association so that they know what input they are typing into. There's also a huge usability difference when the labels are properly associated (user can click on the label to set the focus to the associated input). This is really apparent with checkbox and radio inputs.
Fiddle with example of both on checkboxes. (Note how much easier it is to click on the label rather than the input itself)
As for your opposition... I'm not sure how adding id attributes does any of the "cons" you state. Clutter? nope, valid usable code. Confusing? nope, id's and properly associated labels would be the first thing I'd add if I saw that code. Binds you to a test tool and outside code? how exactly? The fact that it would make your testing crew's life easier is just icing on the cake.
Your first 2 Cons are valid, but I disagree with the last 3.
You could take the stance that you will provide logical element Id's for your testers, but they are responsible for utilizing them with whatever testing tools etc... that they use. This means that you are test/tool agnostic, you just provide the Id's for testing use without necessarily knowing exactly how they will be used.
Adding Id's like this is fairly standard practice for a lot of web apps today.
If possible, their testing tool should fill in the fields based on their name attributes and the form's action attribute if there are multiple forms on the page. These are guaranteed to be as stable as the part of the server answering the POST request.
Ids, field ordering, and other attributes might change due to front-end reasons.
For me it depends. It depends on if the elements can be easily and reliably found without the ID.
In your example, yes, so adding the ID isn't a waste but just isn't necessary. However that's all that is, an example.
In a lot of web pages, as they become more complex and complicated, ID's become your friend, because without it you will need to look at other ways of finding elements.
Especially in the Selenium world, when you come across this problem, you generally turn to CSS and/or XPath selectors.
Other selectors are not bad things, but they can quite slow in older browsers, if you support them.

Hiding input fields with type='hidden' vs using a class with display:none

There are several hidden form fields on my pages that are used for passing data to server side. For debugging purposes, I feel it easier to hide all eligible input fields by just making them all a part of hidden class than setting the type=hidden attribute on each input field.
Whenever I need to debug I could easily modify that class attribute to enter debug mode. Ofcourse both the approaches work in hiding the input fields but I am not sure as to why this approach(hiding via class) isn't much widely used in real life. Can you throw some light on what should be preferred approach ?
<input type="hidden"> won't trigger input validation, auto completion, and other user interaction related events. It's designed to save raw data, without user's direct input.
But a <input type="text">, visually hidden, are still going to be considered as a user interaction component. And on some devices enabled visual aid, it will serve as not hidden, and cannot provide the consistency you expected. That's why it's not preferred to do so.
Eg. a <input type="hidden"> won't auto complete it self, or preserve the inputted data before refreshing a page, or prevent the form from being submitted for a failed type validation can't even be seen.
The CSS approach is bad for usability, and accessibility. Think of someone with CSS disabled (very old mobile phones, people with a screen reader), they won't render your CSS as you might expect, and the input with all of its glory would be displayed to the user.
A hidden input should be used for implied user input, meaning, input that would come from the user, but is implied and does not need to be manually entered.
Your question falls more onto the type="hidden" approach.
I'd recommend using <input type="hidden" /> because it is the standard way of HTML to hold a user's input value. If you use another attribute for type and hide it with css, one problem may arise is that when the css fails to load, the input control will show up.
I think your question is about the best approach for debugging form fields. I recommend keeping them as type='hidden' in your HTML. This is best for you, for your users and for semantic interpretation of the page.
Instead, use a tool like the Chrome Developer Tools to do your debugging. This will let you easily see the values of your hidden fields.