Programing

이름이 ''인 잘못된 양식 컨트롤은 초점을 맞출 수 없습니다.

lottogame 2020. 10. 3. 09:45
반응형

이름이 ''인 잘못된 양식 컨트롤은 초점을 맞출 수 없습니다.


내 웹 사이트에 심각한 문제가 있습니다. Google 크롬에서 일부 고객은 내 결제 페이지로 이동할 수 없습니다. 양식을 제출하려고 할 때이 오류가 발생합니다.

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

이것은 JavaScript 콘솔에서 가져온 것입니다.

필수 속성이있는 숨겨진 필드로 인해 문제가 발생할 수 있음을 읽었습니다. 이제 문제는 html5 필수 속성이 아닌 .net webforms 필수 필드 유효성 검사기를 사용하고 있다는 것입니다.

이 오류가 발생하는 사람은 무작위로 보입니다. 이것에 대한 해결책을 아는 사람이 있습니까?


진술하는 것만으로는 충분하지 않습니다

novalidate 속성을 양식에 추가하면 도움이됩니다.

그것은 문제를 설명하지 않으며 OP는 그것이 왜 도움이 될지 또는 실제로 도움이되는지 이해하지 못했을 수 있습니다.

다음 은 사례를 진정으로 설명하는 답변입니다. 문제를 이해하면 개발에 적합한 솔루션에 도달 할 수 있습니다.

Chrome은 필수이지만 여전히 비어있는 컨트롤에 집중하여 '이 필드를 입력하세요'라는 메시지를 표시 할 수 있도록합니다. 그러나 Chrome이 메시지를 팝업하려는 지점, 즉 양식 제출 시점에 컨트롤이 숨겨져 있으면 Chrome은 컨트롤이 숨겨져 있기 때문에 컨트롤에 집중할 수 없으므로 양식이 제출되지 않습니다.

따라서 문제를 해결하려면 컨트롤이 자바 스크립트에 의해 숨겨 질 때 해당 컨트롤에서 'required'속성도 제거해야합니다.

경고를 잘 사용하려면 이것을 고려하십시오- 유효성 검사에 실패 할 때 필드를 숨기지 마십시오 . 그러나 그것은 엄격한 규칙도 아니고 전혀 규칙도 아닙니다. 아래 댓글에서 언급했듯이

경우에 따라 문제가 전혀 문제가되지 않으며 응용 프로그램의 기능이 손실되지 않습니다. 그러면 오류가 무시 될 수 있습니다.

업데이트 : 2015 년 8 월 21 일

문제의 오류는 조기 유효성 검사로 인해 발생할 수도 있습니다. <button>설정된 유형 속성이 없는 입력 이있는 경우 조기 유효성 검증이 발생할 수 있습니다 . 버튼의 유형 속성을 버튼으로 설정하지 않으면 제출 이 기본 버튼 유형 이므로 Chrome (또는 해당 문제에 대한 다른 브라우저)은 버튼을 클릭 할 때마다 유효성 검사를 수행 합니다. 문제를 해결하려면 페이지에 제출 또는 재설정 이외의 다른 작업을 수행하는 버튼이있는 경우 항상 다음을 수행해야합니다.<button type="button">


novalidate양식에 속성을 추가 하면 도움이됩니다.

<form name="myform" novalidate>

당신의에서 form, 당신은 숨겨진 수도 input가진 required속성을 :

  • <input type="hidden" required />
  • <input type="file" required style="display: none;"/>

(가) form이러한 요소에 초점을 맞출 수 없습니다, 당신은 제거해야 required당신이 정말로 숨겨진 입력을 요구하는 경우이를 처리하는 자바 스크립트 유효성 검사 기능을 모든 숨겨진 입력에서, 또는 구현합니다.


다른 사람이이 문제를 가지고 있다면 저도 같은 경험을했습니다. 주석에서 논의했듯이 숨겨진 필드의 유효성을 검사하려는 브라우저 때문이었습니다. 양식에서 빈 필드를 찾아 초점을 맞추려고했지만로 설정 되었기 때문에 display:none;불가능했습니다. 따라서 오류입니다.

다음과 비슷한 것을 사용하여 해결할 수있었습니다.

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

또한 이것은 Google 크롬에서만 "잘못된 양식 제어" 의 중복 일 수 있습니다.


제 경우에는 다음과 같이 input type="radio" required숨겨진 문제가있었습니다 .

visibility: hidden;

필요한 입력 유형이 경우에도이 오류 메시지가 표시됩니다 radio또는 checkboxdisplay: none;CSS 속성을.

UI에서 숨기고required 속성을 유지 해야하는 사용자 지정 라디오 / 체크 박스 입력생성하려면 대신 다음을 사용해야합니다.

opacity: 0; CSS 속성


이전 답변 중 어느 것도 나를 위해 일하지 않았으며 required속성 이있는 숨겨진 필드가 없습니다 .

내 경우에는 문제가함으로써 발생 된 <form>후를 <fieldset>을 보유하고 첫 아이로 <input>required속성. 제거하면 <fieldset>문제가 해결되었습니다. 또는 양식을 포장 할 수 있습니다. HTML5에서 허용됩니다.

저는 Windows 7 x64, Chrome 버전 43.0.2357.130m에 있습니다.


필수 속성 이있는 숨겨진 (표시 : 없음) 필드가있을 수 있습니다 .

모든 필수 필드가 사용자에게 표시되는지 확인하십시오. :)


나에게 이것은 <select>''값으로 미리 선택된 옵션이 있는 필드가 있을 때 발생합니다 .

<select name="foo" required="required">
    <option value="" selected="selected">Select something</option>
    <option value="bar">Bar</option>
    <option value="baz">Baz</option>
</select>

안타깝게도 플레이스 홀더를위한 유일한 크로스-브라우저 솔루션입니다 ( '선택'상자에 대한 플레이스 홀더는 어떻게 만드나요? ).

이 문제는 Chrome 43.0.2357.124에서 발생합니다.


양식 제출 중에 표시되지 않는 필수 속성이있는 필드가있는 경우이 오류가 발생합니다. 해당 필드를 숨기려고 할 때 필요한 속성 만 제거하면됩니다. 필드를 다시 표시하려는 경우 필수 속성을 추가 할 수 있습니다. 이렇게하면 유효성 검사가 손상되지 않고 동시에 오류가 발생하지 않습니다.


Select2 Jquery 문제의 경우

문제는 HTML5 유효성 검사가 숨겨진 유효하지 않은 요소에 초점을 맞출 수 없기 때문입니다. jQuery Select2 플러그인을 다룰 때이 문제를 발견했습니다.

솔루션 HTML5 validate 이벤트 직전에 조작 할 수 있도록 양식의 모든 요소에 이벤트 리스너를 삽입하고 '유효하지 않은'이벤트를 삽입 할 수 있습니다.

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

확인란 입력에 오류가 발생하면 또 다른 가능성이 있습니다. 체크 박스가 기본값을 숨기고 다른 스타일로 대체하는 맞춤 CSS를 사용하는 경우 유효성 검사 오류시 Chrome에서 초점을 맞출 수없는 오류가 트리거됩니다.

내 스타일 시트에서 이것을 찾았습니다.

input[type="checkbox"] {
    visibility: hidden;
}

간단한 수정은 다음으로 대체하는 것입니다.

input[type="checkbox"] {
    opacity: 0;
}

다음과 같은 코드가있는 경우 해당 메시지가 표시됩니다.

<form>
  <div style="display: none;">
    <input name="test" type="text" required/>
  </div>

  <input type="submit"/>
</form>

예 .. 숨겨진 양식 컨트롤에 필수 필드가 있으면이 오류가 표시됩니다. 한 가지 해결책은 이 양식 컨트롤비활성화하는입니다. 이는 일반적으로 폼 컨트롤을 숨기는 경우 해당 값에 관심이 없기 때문입니다. 따라서이 양식 컨트롤 이름 값 쌍은 양식을 제출하는 동안 전송되지 않습니다.


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


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

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


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.


In my case..

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


There are many ways to fix this like

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

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

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


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

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

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.


Alternatively another and foolproof answer is to use HTML5 Placeholder attribute then there will be no need to use any js validations.

<input id="elemID" name="elemName" placeholder="Some Placeholder Text" type="hidden" required="required">

Chrome will not be able to find any empty, hidden and required elements to focus on. Simple Solution.

Hope that helps. I am totally sorted with this solution.


I came here with the same problem. For me (injecting hidden elements as needed - i.e. education in a job app) had the required flags.

What I realized was that the validator was firing on the injected faster than the document was ready, thus it complained.

My original ng-required tag was using the visibility tag (vm.flags.hasHighSchool).

I resolved by creating a dedicated flag to set required ng-required="vm.flags.highSchoolRequired == true"

I added a 10ms callback on setting that flag and the problem was solved.

 vm.hasHighSchool = function (attended) {

        vm.flags.hasHighSchool = attended;
        applicationSvc.hasHighSchool(attended, vm.application);
        setTimeout(function () {
            vm.flags.highSchoolRequired = true;;
        }, 10);
    }

Html:

<input type="text" name="vm.application.highSchool.name" data-ng-model="vm.application.highSchool.name" class="form-control" placeholder="Name *" ng-required="vm.flags.highSchoolRequired == true" /></div>

Make sure that all of the controls in your form with the required attribute also have the name attribute set


This error happened to me because I was submitting a form with required fields that were not filled.

The error was produced because the browser was trying to focus on the required fields to warn the user the fields were required but those required fields were hidden in a display none div so the browser could not focus on them. I was submitting from a visible tab and the required fields were in an hidden tab, hence the error.

To fix, make sure you control the required fields are filled.


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;

 }

I received the same error when cloning an HTML element for use in a form.

(I have a partially complete form, which has a template injected into it, and then the template is modified)

The error was referencing the original field, and not the cloned version.

I couldn't find any methods that would force the form to re-evaluate itself (in the hope it would get rid of any references to the old fields that now don't exist) before running the validation.

In order to get around this issue, I removed the required attribute from the original element and dynamically added it to the cloned field before injecting it into the form. The form now validates the cloned and modified fields correctly.


My scenario I hope not missed in this lengthy seed of answers was something really odd.

I have div elements that dynamically update through a dialogBox being called in them to load and get actioned in.

In short the div ids had

<div id="name${instance.username}"/>

I had a user: 测试帐户 and for some reason the encoding did some strange stuff in the java script world. I got this error message for a form working in other places.

Narrowed it down to this and a retest of using numeric numbers instead i.e id appears to fix the issue.

참고URL : https://stackoverflow.com/questions/22148080/an-invalid-form-control-with-name-is-not-focusable

반응형