md-select - how to force required? - html

How do I force md-select in multiple mode to behave just like
<select multiple required ... >
?
Here is the fiddle, to show what I mean. In this example, my browser doesn't let me submit form without selecting at least 1 option from the select tag.
I want md-select to behave similarly, but I don't know how can I do that - neither putting 'required' attribute nor adding 'ng-require' directive helps.

You can rely on Angular to do the validation for this, rather than the browser. Here's my forked example:
http://codepen.io/anon/pen/rVGLZV
Specifically:
<button type="submit" ng-disabled="myForm.$invalid">submit</button>
To keep the submit button disabled until the form is valid and,
<form novalidate name="myForm">
To name the form and tell the browser not to do its own validation on it.
You could even add some CSS class for ng-invalid to show red around the invalid fields.
EDIT: Make sure you put an ng-model on your <select multiple>, otherwise the required attribute won't work.

If you don't want to disable submit button but instead trigger error when submit button is hit, you can set the $touched property to true to trigger required alert
yourFormName.mdseletName.$touched=true;

Related

An invalid form control with name='' is not focusable

In Google Chrome some customers are not able to proceed to my payment page.
When trying to submit a form I get this error:
An invalid form control with name='' is not focusable.
This is from the JavaScript console.
I read that the problem could be due to hidden fields having the required attribute.
Now the problem is that we are using .net webforms required field validators, and not the html5 required attribute.
It seems random who gets this error.
Is there anyone who knows a solution for this?
This issue occurs on Chrome if a form field fails validation, but due to the respective invalid control not being focusable the browser's attempt to display the message "Please fill out this field" next to it fails as well.
A form control may not be focusable at the time validation is triggered for several reasons. The two scenarios described below are the most prominent causes:
The field is irrelevant according to the current context of the business logic. In such a scenario, the respective control should be disabled or removed from the DOM or not be marked with the required attribute at that point.
Premature validation may occur due to a user pressing ENTER key on an input. Or a user clicking on a button/input control in the form which has not defined the type attribute of the control correctly. If the type attribute of a button is not set to button, Chrome (or any other browser for that matter) performs a validation each time the button is clicked because submit is the default value of a button's type attribute.
To solve the problem, if you have a button on your page that does something else other than submit or reset, always remember to do this: <button type="button">.
Adding a novalidate attribute to the form will help:
<form name="myform" novalidate>
In your form, You might have hidden input having required attribute:
<input type="hidden" required />
<input type="file" required style="display: none;"/>
The form can't focus on those elements, you have to remove required from all hidden inputs, or implement a validation function in javascript to handle them if you really require a hidden input.
In case anyone else has this issue, I experienced the same thing. As discussed in the comments, it was due to the browser attempting to validate hidden fields. It was finding empty fields in the form and trying to focus on them, but because they were set to display:none;, it couldn't. Hence the error.
I was able to solve it by using something similar to this:
$("body").on("submit", ".myForm", function(evt) {
// Disable things that we don't want to validate.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", true);
// If HTML5 Validation is available let it run. Otherwise prevent default.
if (this.el.checkValidity && !this.el.checkValidity()) {
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
return true;
}
evt.preventDefault();
// Re-enable things that we previously disabled.
$(["input:hidden, textarea:hidden, select:hidden"]).attr("disabled", false);
// Whatever other form processing stuff goes here.
});
Also, this is possibly a duplicate of "Invalid form control" only in Google Chrome
In my case the problem was with the input type="radio" required being hidden with:
visibility: hidden;
This error message will also show if the required input type radio or checkbox has a display: none; CSS property.
If you want to create custom radio/checkbox inputs where they must be hidden from the UI and still keep the required attribute, you should instead use the:
opacity: 0; CSS property
None of the previous answers worked for me, and I don't have any hidden fields with the required attribute.
In my case, the problem was caused by having a <form> and then a <fieldset> as its first child, which holds the <input> with the required attribute. Removing the <fieldset> solved the problem. Or you can wrap your form with it; it is allowed by HTML5.
I'm on Windows 7 x64, Chrome version 43.0.2357.130 m.
Not only required field as mentioned in other answers. Its also caused by placing an <input> field in a hidden <div> which holds an invalid value.
Consider below example,
<div style="display:none;">
<input type="number" name="some" min="1" max="50" value="0">
</div>
This throws the same error. So make sure the <input> fields inside hidden <div> doesnt hold any invalid value.
This issue occurs when you provide style="display: none;" and required attribute to the input field, and there will be validation on submit.
for example:
<input type="text" name="name" id="name" style="display: none;" required>
This issue can be resolved by removing required attribute from the input field from your HTML. If you need to add required attribute, add it dynamically. If you are using JQuery, use below code:
$("input").prop('required',true);
If you need to remove this field dynamically,
$("input").prop('required',false);
You can also make use of plain Javascript if you are not using JQuery:
document.getElementById('element_id').removeAttribute('required');
Yet another possibility if you're getting the error on a checkbox input. If your checkboxes use custom CSS which hides the default and replaces it with some other styling, this will also trigger the not focusable error in Chrome on validation error.
I found this in my stylesheet:
input[type="checkbox"] {
visibility: hidden;
}
Simple fix was to replace it with this:
input[type="checkbox"] {
opacity: 0;
}
It can be that you have hidden (display: none) fields with the required attribute.
Please check all required fields are visible to the user :)
For me this happens, when there's a <select> field with pre-selected option with value of '':
<select name="foo" required="required">
<option value="" selected="selected">Select something</option>
<option value="bar">Bar</option>
<option value="baz">Baz</option>
</select>
Unfortunately it's the only cross-browser solution for a placeholder (How do I make a placeholder for a 'select' box?).
The issue comes up on Chrome 43.0.2357.124.
For Select2 Jquery problem
The problem is due to the HTML5 validation cannot focus a hidden invalid element.
I came across this issue when I was dealing with jQuery Select2 plugin.
Solution
You could inject an event listener on and 'invalid' event of every element of a form so that you can manipulate just before the HTML5 validate event.
$('form select').each(function(i){
this.addEventListener('invalid', function(e){
var _s2Id = 's2id_'+e.target.id; //s2 autosuggest html ul li element id
var _posS2 = $('#'+_s2Id).position();
//get the current position of respective select2
$('#'+_s2Id+' ul').addClass('_invalid'); //add this class with border:1px solid red;
//this will reposition the hidden select2 just behind the actual select2 autosuggest field with z-index = -1
$('#'+e.target.id).attr('style','display:block !important;position:absolute;z-index:-1;top:'+(_posS2.top-$('#'+_s2Id).outerHeight()-24)+'px;left:'+(_posS2.left-($('#'+_s2Id).width()/2))+'px;');
/*
//Adjust the left and top position accordingly
*/
//remove invalid class after 3 seconds
setTimeout(function(){
$('#'+_s2Id+' ul').removeClass('_invalid');
},3000);
return true;
}, false);
});
If you have any field with required attribute which is not visible during the form submission, this error will be thrown. You just remove the required attribute when your try to hide that field. You can add the required attribute in case if you want to show the field again. By this way, your validation will not be compromised and at the same time, the error will not be thrown.
It's weird how everyone is suggesting to remove the validation, while validation exists for a reason...
Anyways, here's what you can do if you're using a custom control, and want to maintain the validation:
1st step. Remove display none from the input, so the input becomes focusable
.input[required], .textarea[required] {
display: inline-block !important;
height: 0 !important;
padding: 0 !important;
border: 0 !important;
z-index: -1 !important;
position: absolute !important;
}
2nd step. Add invalid event handler on the input to for specific cases if the style isn't enough
inputEl.addEventListener('invalid', function(e){
//if it's valid, cancel the event
if(e.target.value) {
e.preventDefault();
}
});
It happens if you hide an input element which has a required attribute.
Instead of using display:none you can use opacity: 0;
I also had to use some CSS rules (like position:absolute) to position my element perfectly.
Yea.. If a hidden form control has required field then it shows this error. One solution would be to disable this form control. This is because usually if you are hiding a form control it is because you are not concerned with its value. So this form control name value pair wont be sent while submitting the form.
I came here to answer that I had triggered this issue myself based on NOT closing the </form> tag AND having multiple forms on the same page. The first form will extend to include seeking validation on form inputs from elsewhere. Because THOSE forms are hidden, they triggered the error.
so for instance:
<form method="POST" name='register' action="#handler">
<input type="email" name="email"/>
<input type="text" name="message" />
<input type="date" name="date" />
<form method="POST" name='register' action="#register">
<input type="text" name="userId" />
<input type="password" name="password" />
<input type="password" name="confirm" />
</form>
Triggers
An invalid form control with name='userId' is not focusable.
An invalid form control with name='password' is not focusable.
An invalid form control with name='confirm' is not focusable.
Another possible cause and not covered in all previous answers when you have a normal form with required fields and you submit the form then hide it directly after submission (with javascript) giving no time for validation functionality to work.
The validation functionality will try to focus on the required field and show the error validation message but the field has already been hidden, so "An invalid form control with name='' is not focusable." appears!
Edit:
To handle this case simply add the following condition inside your submit handler
submitHandler() {
const form = document.body.querySelector('#formId');
// Fix issue with html5 validation
if (form.checkValidity && !form.checkValidity()) {
return;
}
// Submit and hide form safely
}
Edit: Explanation
Supposing you're hiding the form on submission, this code guarantees that the form/fields will not be hidden until form become valid. So, if a field is not valid, the browser can focus on it with no problems as this field is still displayed.
There are many ways to fix this like
Add novalidate to your form but its totally wrong as it will remove form validation which will lead to wrong information entered by the users.
<form action="...." class="payment-details" method="post" novalidate>
Use can remove the required attribute from required fields which is also wrong as it will remove form validation once again.
Instead of this:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" required="required">
Use this:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text">
Use can disable the required fields when you are not going to submit the form instead of doing some other option. This is the recommended solution in my opinion.
like:
<input class="form-control" id="id_line1" maxlength="255" name="line1" placeholder="First line of address" type="text" disabled="disabled">
or disable it through javascript / jquery code dependes upon your scenario.
It will show that message if you have code like this:
<form>
<div style="display: none;">
<input name="test" type="text" required/>
</div>
<input type="submit"/>
</form>
You may try .removeAttribute("required") for those elements which are hidden at the time of window load. as it is quite probable that the element in question is marked hidden due to javascript (tabbed forms)
e.g.
if(document.getElementById('hidden_field_choice_selector_parent_element'.value==true){
document.getElementById('hidden_field').removeAttribute("required");
}
This should do the task.
It worked for me... cheers
There are things that still surprises me... I have a form with dynamic behaviour for two different entities. One entity requires some fields that the other don't.
So, my JS code, depending on the entity, does something like:
$('#periodo').removeAttr('required');
$("#periodo-container").hide();
and when the user selects the other entity:
$("#periodo-container").show();
$('#periodo').prop('required', true);
But sometimes, when the form is submitted, the issue apppears: "An invalid form control with name=periodo'' is not focusable (i am using the same value for the id and name).
To fix this problem, you have to ensurance that the input where you are setting or removing 'required' is always visible.
So, what I did is:
$("#periodo-container").show(); //for making sure it is visible
$('#periodo').removeAttr('required');
$("#periodo-container").hide(); //then hide
Thats solved my problem... unbelievable.
In my case..
ng-show was being used.
ng-if was put in its place and fixed my error.
Wow, a lot of answers here!
If the problem is <input type="hidden" required="true" />, then you can solve this in just a few lines.
The logic is simple and straight-forward:
Mark every required input on page-load with a data-required class.
On submit, do two things: a) Add required="true" to all data-required inputs. b) Remove required="true"` from all hidden inputs.
HTML
<input type="submit" id="submit-button">
Pure JavaScript
document.querySelector('input,textarea,select').filter('[required]').classList.add('data-required');
document.querySelector('#submit-button').addEventListener('click', function(event) {
document.querySelector('.data-required').prop('required', true);
document.querySelector('input,textarea,select').filter('[required]:hidden').prop('required', false);
return true;
}
jQuery
$('input,textarea,select').filter('[required]').addClass('data-required');
$('#submit-button').on('click', function(event) {
$('.data-required').prop('required', true);
$('input,textarea,select').filter('[required]:hidden').prop('required', false);
return true;
}
For Angular use:
ng-required="boolean"
This will only apply the html5 'required' attribute if the value is true.
<input ng-model="myCtrl.item" ng-required="myCtrl.items > 0" />
I found same problem when using Angular JS. It was caused from using required together with ng-hide. When I clicked on the submit button while this element was hidden then it occurred the error An invalid form control with name='' is not focusable. finally!
For example of using ng-hide together with required:
<input type="text" ng-hide="for some condition" required something >
I solved it by replacing the required with ng-pattern instead.
For example of solution:
<input type="text" ng-hide="for some condition" ng-pattern="some thing" >
Not just only when specify required, I also got this issue when using min and max e.g.
<input type="number" min="1900" max="2090" />
That field can be hidden and shown based on other radio value. So, for temporary solution, I removed the validation.
I have seen this question asked often and have come across this 'error' myself. There have even been links to question whether this is an actual bug in Chrome.
This is the response that occurs when one or more form input type elements are hidden and these elements have a min/max limit (or some other validation limitation) imposed.
On creation of a form, there are no values attributed to the elements, later on the element values may be filled or remain unchanged.
At the time of submit, the form is parsed and any hidden elements that are outside of these validation limits will throw this 'error' into the console and the submit will fail. Since you can't access these elements (because they are hidden) this is the only response that is valid.
This isn't an actual fault nor bug. It is an indication that there are element values about to be submitted that are outside of the limits stipulated by one or more elements.
To fix this, assign a valid default value to any elements that are hidden in the form at any time before the form is submitted, then these 'errors' will never occur. It is not a bug as such, it is just forcing you into better programming habits.
NB: If you wish to set these values to something outside the validation limits then use form.addEventListener('submit', myFunction) to intercept the 'submit' event and fill in these elements in "myFunction". It seems the validation checking is performed before "myFunction() is called.
Its because there is a hidden input with required attribute in the form.
In my case, I had a select box and it is hidden by jquery tokenizer using inline style. If I dont select any token, browser throws the above error on form submission.
So, I fixed it using the below css technique :
select.download_tag{
display: block !important;//because otherwise, its throwing error An invalid form control with name='download_tag[0][]' is not focusable.
//So, instead set opacity
opacity: 0;
height: 0px;
}
For other AngularJS 1.x users out there, this error appeared because I was hiding a form control from displaying instead of removing it from the DOM entirely when I didn't need the control to be completed.
I fixed this by using ng-if instead of ng-show/ng-hide on the div containing the form control requiring validation.
Hope this helps you fellow edge case users.

Is it acceptable for a submit button to have a name attribute?

Usually, a submit button works fine without a name attribute. However, there are occasions where there's a need to have two submit buttons for the same form, hence making use of the name attribute to identify which button was clicked on the server side.
To clarify I am talking about: <input type="submit" name="foo">
Yes, it is entirely acceptable.
The specification has explicit rules for how to determine which submit button was successful, which would be useless if you couldn't give the element a name.

Why is the submit button value passed when using the GET method in HTML?

I am using the the "GET" method in a form on my website. For some reason it is passing the value of the submit button to the url. Why is this happening? What am I doing wrong?
Form:
<form method="GET" action="searcht1.php">
<input type="text" name="search"/>
<input type="submit" name="submit">
</form>
Url:
searcht1.php?search=colin+pacelli&submit=Submit
It's supposed to happen. If you don't want that, do not define name attribute on the button. You probably want value instead, to show the user what the button is for.
Also, this question has nothing to do with PHP; it is purely about HTML semantics.
The reason is that the name attribute makes the submit button a “successful control” (in HTML 4.01 terminology) when it is used for form submission. This causes the name=value pair from it to be included in the form data.
Note that in your case, this data is name=foo where foo is the browser-dependent default value of the button. It could be submit, or it could be Lähetä kysely, or something exotic. You can, and normally should, use the value attribute to set this value, since it determines the text displayed in the button. It’s usually not desirable to have a submit button on your English-language appear with e.g. some text in Japanese just because a Japanese-language browser is being used.
So as others have written, the solution (if this is a problem) is to remove the name attribute. But since the value attribute should normally be used, you can make two changes simultaneously by just replacing the attribute name name by the name value, though you might also capitalize the word shown:
<input type="submit" value="Submit">
Try to remove name attribute from submit input
remove the name attribute of the button.....

Exclude radio buttons from a form submit, without disabling them

I'm using some radio buttons to influence the behavior states of a jQuery widget.
That widget can be used in a form but, since these radios don't contain any actual data, I don't want them to submit noise to the server, or cause naming conflict to whoever will use the widget in his form.
Here are two potential solution starts, not yet satisfying though :
remove the name attribute : seems to work fine for other inputs, but turns my radios into checkboxes : it kills the link between them so selecting one doesn't unselect the others. Is there an HTML way (i.e. other than Javascript event) to bind them without a name attribute ?
disable the input : As expected, nothing is submitted, but the radios become grey and can't be clicked. Is there any way that they stay clickable yet unsubmittable, like disabled at submit time ?
As far as possible, I'm rather looking for a cross-browser solution.
Try call a function before submit, that disables the radio buttons.
function disableBtn() {
document.getElementById('idbtn1').setAttribute('disabled', 'disabled');
document.getElementById('idbtn2').setAttribute('disabled', 'disabled');
return true;
}
Then, in form:
<form action="file" method="post" onsubmit="return disableBtn()">
Try this:
<form>
<input type="radio" name="group1" value="1" form="">
<input type="radio" name="group1" value="2" form="">
</form>
This still uses the name attribute which is required for radio buttons, and it also leaves the inputs enabled for interaction. No JavaScript code, no during-submit patching of the document in hope that the submit will turn out fine and destroying the document before submit will leave no visible traces.
The form="" attribute indicates that these input elements are not included in their parent form. Actually you're supposed to put the ID of another existing <form> element in this attribute, but then again, by the HTML standard, you're probably not supposed to exclude radio buttons from a form. So this hack is the only solution to the problem. (Doesn't work in Internet Explorer, but what does today.)
I'm intending to use this method for radio button groups that are in a data table which is populated from a <template> element. In this case, there will be a radio group in each table row, so their number is unknown. But since the name attribute is the only way to build radio button groups, they'll need to get counting names assigned. Since the table data is put in a JSON field before submitting anyway, I don't need field names for a form submit. Radio buttons do need names for themselves, but this method will still exclude them from being submitted.

playframework, input disabled breaks play from passing the value?

I have an input field that is filled in from a previous form(so the input is set to disabled on the second page) and we receive null for the value then. This works:
<input type="text" class="boxtpl" name="${field.name}" value="${user?.email}">
but this doesn't:
<input type="text" class="boxtpl" name="${field.name}" value="${user?.email}" disabled="disabled">
Is there a reason why this seems to break the framework?
Disabled controls shouldn't actually be submitted with the form, so what you're seeing is in fact normal behaviour. According to the HTML form specification:
When set, the disabled attribute has the following effects on an element:
Disabled controls do not receive focus.
Disabled controls are skipped in tabbing navigation.
Disabled controls cannot be successful.
The definition of successful can be found in the same document. It's a bit nonsensical to suggest that Play is broken because of this.
If you want to have a form field that user cannot edit while it should still be sent along when the form is submitted, you can use the read-only attribute, or use JavaScript to disallow user input.
Update: as pointed out in the comments, the following points may also offer a solution:
It's possible that Play still keeps the disabled control's form values in the request object, and just doesn't bind them (so you could retrieve them from the request if needed)
Use a hidden field to keep the form value in case you still want to submit the value, but do not want the user(s) to see the control