Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMLFormElement.reportValidity() ignore "display:none" input fields

I'm sending a form using an ajax call. When the user uses the submit button within the form, this calls a function sendForm(). The function prevents the default (submitting the form), and validates the form (for fields with required) and if the form is valid then makes the ajax call.

Problem is that the form contains some hidden (display:none) elements, which are validated using the resportValidity() call, and therefore the form fails because of the hidden elements, which should not be validated (they are displayed depending on the previous user options).

Below the sendForm() function used:

function sendForm(e) {
  $(e).preventDefault;

  var form = document.getElementById('myForm');

  if (form.reportValidity()) { 

      // form is valid, do ajax call..

  }else{

    alert("Form not valid");

  }
}

So when it does form.reportValidity() I get false because of "empty" required input fields from the inputs with display:none style.

How can I just reportValidity() the form elements without display:none? Thanks!

like image 628
Dovi Avatar asked Nov 01 '25 15:11

Dovi


1 Answers

If you don't want an element to be included in the form when checking for validity, you should disable the element. At the time you set display: none you should also add the disabled attribute.

Documentation

like image 197
ChrisG Avatar answered Nov 04 '25 08:11

ChrisG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!