skip to Main Content

After setting the required prop to false using $( '#field' ).prop( 'required', false );, form.checkValidity() still returns false on the field and form.reportValidity() tries to focus on the element.

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

The element of input type date does not have a name and is hidden, while other elements of type select do not seem to have this issue.

Full error message (name attribute added):

An invalid form control with name='' is not focusable.
<input id="ipt-arrival-date" name="arrival" type="date" onfocus="this.showPicker()" min="2024-09-04" max="2024-09-08" class="">

From the error it shows that the required prop is not there at the time the error shows.

The form is too large to post the complete code.

Any ideas?

2

Answers


  1. Chosen as BEST ANSWER

    Happy that I found out what was happening, though it was quite frustrating at first!

    So I "unhided" the parent container in de dev console and the actual error popped up, which was not about it being required or not, but about the maximum date set for the element and the value not being valid for that restriction.

    enter image description here


  2. To quote MDN WebDocs:

    A boolean attribute in HTML is an attribute that represents true or false values. If an HTML tag contains a boolean attribute – no matter the value of that attribute – the attribute is set to true on that element.

    required is a boolean attribute! The pure existence of this attribute will make it true no matter the value! By using . prop('required', false) you will set the value to false but as specified above it has no effect. You effectively add the attribute and make it true that way. To actually remove the required attribute you have to use .removeAttr() in jQuery.

    Vanilla JS proof:

    window.addEventListener('DOMContentLoaded', function() {
      INPUT_A.setAttribute('required', false);
      console.log(`Input A: ${INPUT_A.required}`);
      
      INPUT_B.removeAttribute('required');
      console.log(`Input B: ${INPUT_B.required}`);
    });
    <input id="INPUT_A" required>
    <input id="INPUT_B" required>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search