Avoid validation on hidden elements

Asked

Viewed 56 times

0

Good night, you guys,

I need a light. I am creating a dynamic system, which creates a form from a JSON.

It turns out that in some cases, I create a select, and according to its value, I display a fieldset or another.

The form validation is also being done dynamically creating a eventListener for each input generated, where I do the checks with the checkValidity() and the reportValidity() to deal with mistakes.

My problem is that when a fieldset is activated, the other receives a css class that applies a None display, only even as Hidden, the fields within that fieldset (but that are within the same form) try to be treated, as the field is not visible generates an error in the browser console: "An invalid form control with name='field[]' is not focusable.".

I created a simple function that generates these validations in javascript which is like this

function validateField (ob) {
  ob.addEventListener("focusout", function (){
    let msg = ob.validationMessage, p = document.createElement("p");
    
    if(ob.nextSibling) ob.nextSibling.remove();
    if(ob.checkValidity() == false) {
      p.className = "msg-error";
      p.innerHTML = msg;
      ob.parentNode.insertBefore(p, ob.nextSibling);
    }
  });
}

I was taking a look at the new html command but I need to apply in the form, as I am inside the same form I cannot apply it in general, I need to apply it either in the fieldset that has a group of inputs, or in those inputs directly.


In the end I managed to solve my problem by creating a function that applies the disabled attribute to all fields that were hidden. With this I was able to pass checkValidity() validation It was enough to make a element.toggleAttribute("disabled") in the hidden elements to solve.

2 answers

1

Add novalidate to the Formulars

<form name="myform" novalidate>

And on the buttons, put the type=Button

<button type="button">

Tbm can use Hidden directly

<input type="hidden" required />

Or

<input type="text" style="display: none" required />
  • 1

    I could not apply the rule in the form because other fields still needed to be validated and the other methods still fall into checkValidity() validation. I managed to create a function that applied a disabled in the fields and solved the problem.

0


I was able to solve my problem by creating a function that applies the disabled attribute to all fields that were hidden. With this I was able to pass the checkValidity validation()

  • I understand your question, but the answer is precisely the conclusion. I just can’t define how to answer today because the platform does not allow, only tomorrow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.