I'm trying to get HTML patterns to work. The behaviour I expect is that as soon as text that doesn't match a given pattern is entered into an input, the edges of the input will turn red (error state), and go back to normal as soon as the text matches the pattern again. This is the pattern I'm using - for non-regex people, it allows characters from the alphabet, both upper and lower case, and requires exactly three characters.
<input type="text" pattern="[A-Za-z]{3}">
I couldn't get this behaviour working reliably in my project, so I took this example from W3Schools: https://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml5_input_pattern to test it.
When I load it in Firefox (latest version):
After entering invalid data for the first time after the page renders, I need to click somewhere else (the input needs to lose focus) for the input to go into error state.
After this, if I enter valid data and click somewhere else, the state of the input goes back to normal. (expected behaviour)
However, if I then enter invalid data without the input losing focus, the error state is still not triggered.
When I test it in Chrome (latest version, again), the input simply never turns red, no matter what I enter or where the focus is.
Not only does the pattern not behave how I expected, but it does not behave consistently from browser to browser.
Can anyone explain this? Is this an official feature? I know it doesn't behave consistently on mobile browsers, but it should on major desktop browsers (platform in Win7 FWIW)
HTML5 validation styled differently across browsers. While supporting browsers will all prevent a form submission if it's invalid, everything outside of that is a browser design decision.
You can attempt to enforce certain behaviors using JavaScript. For example, if you want some kind of immediate feedback for invalid input, you can attach a handler to the input event.
document.querySelector('input').addEventListener('input', function(e) {
if (!e.currentTarget.checkValidity()) {
e.currentTarget.classList.add('invalid');
} else {
e.currentTarget.classList.remove('invalid');
}
});
.invalid {
background-color: red;
}
<form>
<input type="text" pattern="[A-Za-z]{3}">
<input type="submit">
</form>
Obviously you'll want better custom styling, and something that doesn't clash with the native "invalid state" styling of major browsers, but this at least gets you started in the right direction.
You could also force the browser to report validity on the input event. But you may find most browsers' behavior for reportValidity is a bit too loud to show on each invalid input.
document.querySelector('input').addEventListener('input', function(e) {
e.currentTarget.reportValidity();
});
<form>
<input type="text" pattern="[A-Za-z]{3}">
<input type="submit">
</form>
Related
Is there a way to prevent the LastPass browser extension from filling out a HTML-based form with an input field with the name "username"?
This is an hidden field, so I don't want any software to use this field for their purposes:
<input type="text" name="username" id="checkusername" maxlength="9" value="1999" class="longinput" style="display:none">
The solution should not be like "rename the input field".
Adding
data-lpignore="true"
to an input field disabled the grey LastPass [...] box for me.
Sourced from LastPass.com
Two conditions have to be met:
The form (not the element) needs to have autocomplete="off" attribute
Lastpass user needs to have this option enabled:
(old) Settings > Advanced > Allow pages to disable autofill
(new) Account Options > Extension Preferences > Advanced > Respect AutoComplete=off: allow websites to disable Autofill
So this depends on both user and the developer.
What worked for me is having word "-search-" in the id of the form, something like <form id="affiliate-search-form"> - and lastpass doesn't add its elements onto the form inputs. It works with something simpler like <form id="search"> but doesn't work with <form id="se1rch">
I know I'm late to the party here, but I found this when I was trying to stop lastpass from ruining my forms. #takeshin is correct in that autocomplete is not enough. I ended up doing the hack below just to hide the symbol. Not pretty, but I got rid of the icon.
If any lastpass developers are reading this, please give us an attribute to use, so we don't have to resort to stuff like this.
form[autocomplete="off"] input[type="text"] {
background-position: 150% 50% !important;
}
I think lastpass honors the autocomplete="off" attribute for inputs, but I'm not 100% sure.
EDIT
As others have pointed out. this only works if the user has last pass configured to honor this.
For me worked either type=search which is kinda equal to text or using role=note.
You can check the LastPass-JavaScript but it's huge, may be you can find some workaround there, from what I saw they only check 4 input types, so input type=search would be one workaround:
!c.form && ("text" == c.type || "password" == c.type || "url" == c.type || "email" == c.type) && lpIsVisible(c))
Also those are the role-keywords they seem to ignore:
var c = b.getAttribute("role");
switch (c) {
case "navigation":
case "banner":
case "contentinfo":
case "note":
case "search":
case "seealso":
case "columnheader":
case "presentation":
case "toolbar":
case "directory":`
I checked LastPass' onloadwff.js, prepare for 26.960 lines of code :)
Add "search" to input id
<input type="text" name="user" id="user-search"/>
Bit late to the party but I have just achieved this with modifying the form with:
<form autocomplete="off" name="lastpass-disable-search">
I guess this fools lastpass into thinking that it's a search form. This does not work for password fields however! Lastpass ignores the name field in this case.
The only way I've managed to do this is to add the following directly at the top of the form:
<form autocomplete="off">
<div id="lp" ><input type="text" /><input type="password" /></div><script type="text/javascript">setTimeout(function(){document.getElementById('lp').style.display = 'none'},75);</script>
</form>
It causes a nasty flicker but does remove the autofill nonsense - though it does still show the "generate password" widget. LastPass waits until domready and then checks to see if there are any visible password fields, so it's not possible to hide or shrink the mock fields above.
This ES6 style code was helpful for me as it added data-lpignore to all my input controls:
const elements = document.getElementsByTagName("INPUT");
for (let element of elements) {
element.setAttribute("data-lpignore", "true");
}
To access a specific INPUT control, one could write something like this:
document.getElementById('userInput').setAttribute("data-lpignore", "true");
Or, you can do it by class name:
const elements = document.getElementsByClassName('no-last-pass');
for (let element of elements) {
element.setAttribute("data-lpignore", "true");
}
For this latest October 2019 buggy release of Lastpass, this simple fix seems to be best.
Add
type="search"
to your input.
The lastpass routine checks the type attribute to determine what to do with its autofill, and it does nothing on this html5 type of "search." This fix is mildly hacky, but it's a one line change that can be easily removed when they fix their buggy script.
Note: After doing this, your input might appear to be styled differently by some browsers if they pick up on the type attribute. If you observe this, you can prevent it from happening by setting the browser-specific CSS properties -webkit-appearance and -moz-appearance to 'none' on your input.
None of the options here (autocomplete, data-lpignore etc.) prevented LastPass from auto-filling my form fields unfortunately. I took a more sledge-hammer approach to the problem and asynchronously set the input name attributes via JavaScript instead. The following jQuery-dependent function (invoked from the form's onsubmit event handler) did the trick:
function setInputNames() {
$('#myForm input').each(function(idx, el) {
el = $(el);
if (el.attr('tmp-name')) {
el.attr('name', el.attr('tmp-name'));
}
});
}
$('#myForm').submit(setInputNames);
In the form, I simply used tmp-name attributes in place of the equivalent name attributes. Example:
<form id="myForm" method="post" action="/someUrl">
<input name="username" type="text">
<input tmp-name="password" type="password">
</form>
Update 2019-03-20
I still ran into difficulties with the above on account of AngularJS depending upon form fields having name attributes in order for ngMessages to correctly present field validation error messages.
Ultimately, the only solution I could find to prevent LastPass filling password fields on my Password Change form was to:
Avoid using input[type=password]entirely, AND
to not have 'password' in the field name
Since I need to be able to submit the form normally in my case, I still employed my original solution to update the field names 'just in time'. To avoid using password input fields, I found this solution worked very nicely.
Here's what worked for me to prevent lastpass from filling a razor #Html.EditorFor box in Chrome:
Click the active LastPass icon in your toolbar, then go to Account Options > Extension Preferences.
On this screen check "Don't overwrite fields that are already filled" (at the bottom)
Next, click "advanced" on the left.
On this screen check "Respect AutoComplete=off: allow websites to disable Autofill".
I did not need to do anything special in my ASP cshtml form but I did have a default value in the form for the #Html.EditorFor box.
I hope this helps and works for someone. I could not find any Razor-specific help on this problem on the web so I thought I'd add this since I figured it out with the help of above link and contributions.
For someone who stumbles upon this - autocomplete="new-password" on password field prevents LastPass from filling the password, which in combination with data-lpignore="true" disables it at all
Try this one:
[data-lastpass-icon-root], [data-lastpass-root] {
display: none !important;
}
Tried the -search rename but for some reason that did not work. What worked for me is the following:
mark form to autocomplete - autocomplete="off"
change the form field input type to text
add a new class to your css to mask the input, simulates a password field
css bit: input.masker {
-webkit-text-security: disc;
}
Tried and tested in latest versions of FF and Chrome.
type="hidden" autocomplete="off"
Adding this to my input worked for me. (the input also had visibility: hidden css).
Update NOV 2021
I have noticed that all LastPass widgets are wrapped in div of class css-1obar3y.
div.css-1obar3y {
display: none!important;
}
Works perfectly for me
None of these work as of 10/11/2022.
What I did was add the following to a fake password field
<input id="disable_autofill1" name="disable_autofill1"
style="height:0; width:0; background:transparent;
border:none;padding:0.3px;margin:0;display:block;"
type="password">
This seems to be enough to minimize the size this element takes on screen (pretty much 0 for me) while still not triggering last pass's vicious algorithm. Put it before the real password field.
I'm sure a variant of this could be used to fool last pass for other fields where we don't need autofill or to suggest a new password.
Thanks for spending time to read this
I have a form where is call a JS function to copy the html content of a DIV to a hidden form field so that I can submit this with the form. It works fine on desktop webkit broswers and also on mobile safari on iPad. However when I run the application in fullscreen mode (by saving a shortcut on home screen), this does not work.
Here's my code
JS function:
function update_script_in()//copies scripts and submits the form
{
$("#script_in").html($("#scriptContent").html());
$('#ResiForm').submit();
}
form submission:
<input type=submit value="Submit" onclick="update_script_in()">
Thanks for your help
This is quite old, but after googling around to solve the same issue for me, I have not found a solution. Looks like some weird behaviour from iPad (easily reproducible, no way to fix, at least that I found): the target input field gets changed indeed, but the posted value is the original one (???)
So just in case a workaround is useful to somebody, instead of applying the changes from the contenteditable div on form submit, I apply the changes whenever the div is changed (no on change event for contenteditable divs, so really it is done on blur event):
<div id="editor_inline_core_body" class="inputbox editor-inline" contenteditable>[initial value here]</div>
<input type="hidden" id="jform_core_body" name="jform[core_body]" value="[ initial value here]" />
<script>
jQuery('#editor_inline_core_body').blur(function() {
var value = jQuery('#editor_inline_core_body').html();
jQuery('#jform_core_body').val(value);
return true;
});
</script>
Less efficient, but at least it works. If you want a bit more of efficiency, you can check old and new values using also focus event, but at least I do not think it is a big deal or worth the added complexity.
The site I am editing has a search form. For the record, there are several other forms on the site, contact and the like. This is the only one with an issue.
Upon submission of the form, SOME of the styling is lost in IE9 (possibly other versions of IE, haven't tested that yet). Primarily, the margins and colors set in html and body appear to have been lost. Menus, banner, text, etc all appear to retain styles. All styles are on one sheet, that are used here...
Any helpful advice?
Here is the contents of the search page and the php used to check for the form, if that helps, and the css that I think is lost.
EDIT: The page is a search page, with almost nothing on it. A search reloads the same page, while displaying results from the search function. Thus, the same embedded sheets should be embedded, the same html is displayed as far as I can see... if this helps the discussion any. Still sifting to find some type of error. IE dev tools also seem to indicate that this error occurs in previous versions of IE as well, when viewed in IE7-8...
THE HTML:
<div id="search">
<br />
<div style="float:right;font-size:.8em;">
<form name="form_sidesearch" action="search.html" method="post">
<input type="hidden" name="action" value="search" />
<input type="text" name="search_value" value="<?php echo $systems_primary->search_value ?>" />
<input type="submit" name="submit_search" value="Search Website" />
</form> <br />
</div>
</div>
<?php echo stripslashes($search_results);
THE PHP:
<?php
// -- Begin Search --------------------------------------------------------------------------------------
if($_REQUEST["action"] === "search")
{
if(strlen($_REQUEST["pg"]) <= 0)
{
$_REQUEST["pg"] = 1;
}
$search_results = $systems_primary->search_website("index",urldecode($_REQUEST["search_value"]),"<div class=\"listing ui-corner-all\">{ENTRY_TITLE}{ENTRY_CONTENT} ...read more</div><br /><br />",345,"all",10,$_REQUEST["pg"]);
}
// -- End Search ----------------------------------------------------------------------------------------
?>
THE LOST CSS (could be more):
html {
background-color:#F6E6C8;
font-size:16px;
font-family:Helvetica;
}
body {
width:1027px;
margin:0 auto;
background-color:#ffffff;
font-family: arial, 'times new roman', sans-serif;
}
Elaboration: The actual thing that happens is that the page content as a whole is shifted left and remains left aligned instead of using the auto margins to stay centered. Additionally, the html background color is lost. The styles for the search fields are also lost or ignored. Not sure what else might be altered.
Typically when styling is lost after submitting a form, especially when it's an Ajax operation and not a full page reload, it's because there was some styling applied using JavaScript or jQuery that did not get reapplied when the updated portion of the page was reloaded. This could involve additional elements being created, or it could involve CSS classes being added to 1 or more elements.
This is especially likely to happen with the styling of HTML form elements, because in some cases heavy styling of certain form elements can only be done with the help of JavaScript or jQuery.
In such cases, identify the JavaScript or jQuery that styled the relevant content when the page first loaded, and then reapply it after the page has been updated (after an Ajax call has completed successfully, or after the browser has reloaded the page or loaded a new page).
Failing that, compare the HTML for the page before and after and see what changed. There may be a CSS class on the body tag or a container class that's not getting consistently set. If a new page is loaded, a different set of CSS files may be getting downloaded, or there may be an embedded style sheet that one page has but another does not.
Failing that, verify that the HTML and CSS are valid. Some browsers are more forgiving than others when rendering invalid code. What may seem like a browser bug could be caused by bad code.
If all of that turns up nothing and it seems increasingly likely that the problem is caused by an obscure browser bug, then reduce the code to the simplest possible state in which the problem can be consistently reproduced, and try to identify more clearly exactly what the nature of the bug is. This will make it easier to search for possible fixes and to ask for help. And in the course of reducing the code, if the problem suddenly disappears, the last code removed may turn out to be at least partly responsible for the problem.
Conversely, when it seems like there's no rhyme or reason to a problem, it's sometimes helpful to reimplement the code from scratch, to see if the problem still occurs. If the problem starts to occur at some point while writing the code, then likewise the last code that was added may be at least partly responsible for the problem.
You can do something like this...
$('#yourForm").on('submit',function(e){
$(this).css({
// reasign all the atributes you lost
});
e.preventDefault();
});
I'm trying to use HTML5 client-side validation outside a form/submit context, but cannot see how to display the validation error bubbles. Consider the following:
<input type="text" id="input" pattern="[0-9]" required oninvalid="alert('yes, invalid')">
<button onclick="alert(document.getElementById('input').checkValidity())">Check</button>
Everything works as expected, with the correct value being returned from checkValidity, and the invalid event being sent and displayed, but how do I programmatically display the validation error bubble?
If you're talking about this bubble:
See ScottR's comment to this answer instead.
...then my testing shows that both Firefox and Chrome display it when calling checkValidity on an element wrapped in a <form> (testcase), but not on a standalone element (testcase).
There doesn't seem to be a mechanism to display it when there's no form, and the spec doesn't even say it has to be displayed in response to programmatic checkValidity calls (on the element or the form) -- only when submitting a form.
So for now, wrap your elements in a form, even if you will not actually submit it.
Better yet, use your own validation UI, this will shield you from future changes in the browsers in this underspecified area.
Try using required="required" and getting rid of the oninvalid handler unless you really need it.
http://blog.mozilla.com/webdev/2011/03/14/html5-form-validation-on-sumo/
Example of this working: https://support.mozilla.com/en-US/users/register
Just set manually "invalid" attribute to incorrect fields.
Small example:
var form = $('#myForm').get(0);
if(typeof formItem.checkValidity != 'undefined' && !formItem.checkValidity()) {
$('input:required').each(function(cnt, item) {
if(!$(item).val()) {
$(item).attr('invalid', 'invalid');
}
});
return false;
}
I have a bunch of optional "write-in" values for a survey I'm working on.
These are basically a radio button with a textbox within the answer field - the idea being that you would toggle the button and write something into the box.
What I'd like to do is have the radio button toggled whenever a user clicks in the text field - this seems like a use-case that makes a lot of sense.
Doing this:
<input type="radio" id="radiobutton"><label for="radiobutton">Other: <input type="text" id="radiobutton_other"></label>
works fine in Chrome (and I am guessing, other WebKit browsers as well), but there are weird selection issues in Firefox, so I'm assuming its a non-standard practice that I should stay away from.
Is there a way to replicate this functionality without using JavaScript? I have an onclick function that will work, but we're trying to make our site usable for people who might have NoScript-type stuff running.
Putting an input inside a label actually has a slightly different meaning. It doesn't make the input itself a label, it implicitly associates the label with the input in the same way as if they were linked by a for/id.
However, this only happens when the label doesn't already have a for attribute to override that (see HTML4 s17.9: “When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the element's contents.”). It is unclear according to spec what should happen when both containment and for are present.
(And also it doesn't work in IE, which makes the point moot in practical terms.)
No, you'll need some scripting for this.
<input type="radio" id="radiobutton">
<label for="radiobutton_other">Other:</label>
<input type="text" id="radiobutton_other">
<script type="text/javascript">
var other= document.getElementById('radiobutton_other');
other.onchange=other.onkeyup= function() {
if (this.value!=='')
document.getElementById('radiobutton').checked= true;
};
</script>
It (an input inside a label) validates just fine as HTML 4.01. One potential issue I can see with your code is that both radio elements have the same ID in your example. Element IDs must be unique in HTML and XHTML documents and you should use the name attribute instead to identify a radio group.
If you are still having trouble after changing this, you will have to move the input outside of the <label> element and use scripting.