ChatGPT解决这个技术问题 Extra ChatGPT

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?

If you think that it might be due to hidden required fields, maybe you should check if in some cases those fields remain blank? For example, if you fill in user_id from session, or something similar, in certain cases it might remain blank?
Agreed. Open the developer console (F12) in Google Chrome and examine the values of the fields to see if the values for these fields are blank.
Thank you for your comment. It doesnt make any sence to me though? I have a simple asp.net form, which uses asp.net form controls. The input controls is generated by the framework.
I checked and there are values in the input fields. I have one hidden input field which also has a value.
I think It happens when the field is required but is not "visible" in general terms. It happen to me in a form splitted into several tabs the field who triggered the error is in a tab that is not active at the moment of submit I removed required attribute from field and did specific validation

I
Igwe Kalu

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


This problem may arise when a page is built & tested with a browser that doesn't support clientside validation or doesn't prevent the form submission (see Safari). The next developer or user with a browser that actually prevents form submission on clientside errors (see Chrome; even on hidden form elements) runs into the problem of an inaccessible form as one can't submit the form and doesn't get any message from the browser or site. Preventing validation altogether via 'novalidate' is no correct answer as clientside validation should support user inputs. Changing the website is the solution.
Thanks for the detailed answer. Omitting required or adding novalidate is never a good workaround.
This should be the correct answer. If you are using html5 client side validation, adding novalidate fixes one problem while creating another. To bad Chrome wants to validate a input that isn't shown (and thus shouldn't be required).
Just leaving en example in my case, had a hidden number field where the default value wasn't dividable evenly by the step size. Changing the step size solved the issue.
@IgweKalu good call. I ran into this implementing TinyMCE over a textarea field. TinyMCE hides the original form field (which was "required") and triggers this error. Solution, remove the now hidden "required" attribute from the form and rely on other method to ensure it is filled in.
J
Jonathan Leffler

Adding a novalidate attribute to the form will help:

<form name="myform" novalidate>

Thank you for your comment. But i wonder what security risks would come with that? If any? Or does it simply tell the browser not to validate the input fields inside the form?
It’s not a security risk. (Relying on client-side checks is.) It’s a usability problem.
I tried and found that "novalidate" is indeed required. Only adding a form name does not work.
Adding novalidate also stops client side validation, such as with the Rails Simple Form gem. Better to make the problem fields not required, per Ankit's answer + David Brunow's comment.
I discovered that "An invalid form control with name='' is not focusable." also shows if the inputs are in a <fieldset>
I
IgniteCoders

In your form, You might have hidden input having required attribute:

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.


I noticed that this can also happen with fields that are of type "email" set to display none, the problem caused by Chrome trying to validate the format.
It doesn't need to have required. pattern alone can cause this problem.
In my case, the form fields were not type="hidden" they were simply out of view, eg in a form with tabs.
I have two forms, one with both an <input type="hidden" required /> and another with an <input type="text" style="display: none" required />, and the only that is displaying the error in Chrome is the display: none, while the "hidden" one submits fine.
This is the correct answer. Chrome is attempting to validate a field which has been hidden in CSS. The is preventing it from showing its validation warning message, and it's alerting you of this fact.
C
Community

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


If you feel inclined to vote this answer down, please leave a comment to let me know why. I would rather remove the answer if it contains bad information than leave it here and mislead the community.
I won't down vote, but feel this code uses a brute-force "masking the problem" approach. It certainly has usefulness when dealing with legacy code, but for newer projects I would recommend looking at your problem a little harder. This answer also applies to using "novalidate" on the form tag, but that's a little more visible. +1 for disabled instead of removing required.
To give a little bit of context, I was in exactly in the situation of "dealing with legacy code" when I ran into this problem. I fully agree that it's a hack. Much better to design the markup so that you don't encounter this situation. However, with legacy codebases and inflexible CMS systems, this is not always possible. The approach above of disabling rather than using "novalidate" was the best I way I could think of to solve the problem.
I agree with the approach of disabling hidden fields. Removing their 'required' attributes loses the information should they be shown again later. Re-enabling them would keep this, however.
I love this solution, and think it works nicely when you have a form with inputs that are variably displayed or hidden based on the selected values of other inputs. This preserves the required settings, and still allows the form to submit. Even better, if validation fails and the user does something completely different, there are no additional resets needed.
G
Gus

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


same issue with exception that i am using selectivity.js library which hide the current select box and show an alternative js box with js and css. when i use required on it throws this error form-field.js:8 create:1 An invalid form control with name='listing_id' is not focusable. cny sugestion how can i work it arround.
@InzmamGujjar as I understood, your js plugin is creating another select input with its own classes. Maybe altering the plugin CSS classes or selecting the created input name="" instead of the original one?
Helpful answer. I would add if you want to preserve the same layout/styling as display: none, add a position: absolute. Display: none removes the element AND the space it takes up on the page, but visibility: hidden only hides the element visually.
@Gus - Wonderful solution, this worked for me!
Don't forget pointer-events: none; as well to make sure the invisible element doesn't steal clicks away from any elements that might end up stacked below it. You can also fine tune the position of the validation popup so it aligns up with your custom replacement: transform: translate(2rem, 1.5rem);
P
Pere

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.


Had the same problem, thanks for the hint. Managed to solve it with your solution, it is odd.
Thank you, this was the problem in my case as well.
in my case this hint help me
Fieldsets were my problem, as well. In my case, the answer was found here: stackoverflow.com/a/30785150/1002047 Appears to be a Chrome bug (since the HTML in question validates using W3C's validator). Simply changing my fieldsets to divs solved the problem.
@Pere, I corrected the issue with another way, the answer by "abhinav kinagi" below provided the clue, there were other fields that are having validations that further caused the same error (unfocussable error). Hence i had to remove the validation attributes during hide() and add it again while show() in Jquery.
A
Abhinav Kinagi

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.


Worked for me. Thanks
Hi , In my case it is due to invalid Value from DB for one particular form:input field. Is there any way to cancel the validation only for the .hide() fields ?
In my scenario I had a min value of 1 but a value being pulled through from the database of 0 which was held within a hidden tab.
S
Sam

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;
}

This was also the solution that I found to work best. It allows the error message to actually display near the invisible form controls.
C
Community

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.


S
SudarP

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);          
});

g
ghuroo

It can be that you have hidden (display: none) fields with the required attribute.

Please check all required fields are visible to the user :)


A
Ayesha

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');

m
maniempire

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.


Hint: $("input").attr("required", "true"); or $("input").prop('required',true); contrary you can remove the attribute / property. >> jQuery add required to input fields
I
Inc33

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();
   }
}); 

replacing display:none with position: absolute; opacity: 0; to my styled input was sufficient. thanks.
M
Mouneer

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.


U
Umar Asghar

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.


K
KyleMit

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>

i know it's the same i just make an example , some people they understand things better with codes :D
I had the same error, <input type="name" name="name"> , it gave me a rough time. You should pay attention to detail when debugging such errors
@DennisKiprotich you mean without required and still gave you this error?
Yes, without it
K
Kartik Shenoy

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.


Thanks for this idea! It was useful to me to toggle ALL sometimes-hidden form elements regardless of whether the individual ones are required or not, so my logic is nice and simple :)
u
u01jmg3

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


C
Community

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.


G
Gustavo Soler

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.


C
Chareesa Graham

In my case..

ng-show was being used.
ng-if was put in its place and fixed my error.


Saved my day. Thanks
N
Nick Taras

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

K
Khachornchit Songsaen

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

d
deerawan

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.


Hit the up button, this was my issue. Min was higher than the default value of a number input.
s
sudip

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;

 }

J
J.D. Mallen

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.


S
SoliQuiD

Let me put state my case since it was different from all the above solutions. I had an html tag that wasn't closed correctly. the element was not required, but it was embedded in a hidden div

the problem in my case was with the type="datetime-local", which was -for some reason- being validated at form submission.

i changed this

<input type="datetime-local" />

into that

<input type="text" />

K
Kent

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.


K
Kevin Marmet

I wanted to answer here because NONE of these answers, or any other Google result solved the issue for me.

For me it had nothing to do with fieldsets or hidden inputs.

I found that if I used max="5" (e.g.) it would produce this error. If I used maxlength="5" ... no error.

I was able to reproduce the error and clearing of error several times.

I still do not know why using that code produces the error, as far as this states it should be valid, even without a "min" I believe.


Mine was solved by a similar way, but the config was min='-9999999999.99' max='9999999999.99'.