How to display HTML5 check if inputElement.validity.valid == false?

So, I have a form, but I don’t need to send information to the server yet ... I just need to run the fields through the built-in HTML5 validation conditions (for example, by email, etc.), and if true, just follow certain function ...

So far I have come up with this ...

function checkform() { var /* all the elements in the form here */ if (inputElement.validity.valid == 'false') { /* Submit the form, this will cause a validation error, and HTML5 will save the day... */ } else { navigateNextStep(); } } 

That logic I came up with so far, and a little back, because I imagine, it is SIGNIFICANT that there is an invalid value, therefore, triggering validation hints ...

My only problem with the above logic is that I have about 7-8 input elements, and I find an option to do the following rather than the "dirty" one:

 var inputs = document.getElementsByTagName("INPUT"); if (!inputs[0].validity.valid && !inputs[1].validity.valid && ...) 

Ideas?

+6
source share
3 answers

You can simply call formEl.checkValidity() ... This will return a boolean indicating whether the whole form is valid and discard the corresponding invalid events otherwise.

Specification

Brief JSFiddle to play with

I'm not sure if you expect to submit a form to run a browser validation user interface. A call to formEl.submit() seems to produce a view regardless of the validation state. This is noted at the bottom of the H5F Project Page , which states:

Safari 5, Chrome 4-6, and Opera 9.6+ all block form submissions until validation of the entire form of control constraints is performed.

When submitting a form, Opera 9.6+ will focus on the first invalid field and invoke a user interface block indicating that this is incorrect.

Safari 5.0.1 and Chrome 7 removed the form submission lock if the form is not valid, most likely due to outdated forms no longer represent older sites.

+16
source

Okay, so this is inconvenient ... Thanks to Domenik and a good "Google", I found an alternative solution ...

I started the for loop, checking if each of the input elements was valid or not through the imputElement.validity.valid method, which returned a boolean ...

For each element that was valid, I incremented the variable by 1 and included a conditional statement in the loop to check if that variable was enlarged enough to fulfill the navigation function ...

If an invalid field appeared, the if statement would never execute and (the fun part here), the browser will still check the fields, pops up, saying which fields were broken and user correction is needed ... :-)

For the cycle ...

 for (i=0;i<8;i++) { if (inputs[i].validity.valid) hg++; } if (hg==8) skimregform(); 
+1
source

You can programmatically run a check for each field in your form, even if you set the event.preventDefault () function.

  document.forms["form_id_name"].reportValidity(); 
0
source

Source: https://habr.com/ru/post/890462/


All Articles