I'm working on a complex multipage form using HTML, Bootstrap and JavaScript.
What I'm trying to figure out is to validate each section of the multipage form and check if all required fields (if any) are actually valid so that the user can proceed to next section in the form.
The following code snippet is a simplification of my modified form:
<div >
<form id="myform">
<div >
<div >
<div >
<fieldset>...</fieldset>
<input required id="input-field-1">
</div>
<div >
<fieldset>...</fieldset>
<select required id="input-field-2">
</div>
<div >
<fieldset>...</fieldset>
<div >
<input required id="input-field-3">
</div>
</div>
<div >
<fieldset>...</fieldset>
<div >
<div >
<div >
<input required id="input-field-4">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
What is the most efficient way of getting all required fields? For now I'm iterating through each item in the section-1 and get the inner parts to check validity. But using my code below, it will not work on complex nested nodes. How to prevent that?
function find("required", section_number) {
let elements = document.getElementById("form_section_" section_number);
let children = document.getElementById("form_section_" section_number).children;
console.log(children);
for(var i=0; i<children.length; i ){
console.log(children[i].childNodes.length);
if(children[i].childNodes.length == 0){
if (children[i].childNodes.required) {
console.log('✅ element is required');
} else {
console.log('⛔️ element is not required');
}
}
else{
for(var y=0; y<children[i].childNodes.length; y ){
console.log("inner loop = " i ":" y);
if (children[i].childNodes[y].required) {
console.log('✅ element is required');
} else {
console.log('⛔️ element is not required');
}
}
}
}
return false;
}
CodePudding user response:
If you just want to check if your form is valid, use checkValidity()
. If you want some custom handling, you could try selecting all the possible fields and then loop over them to validate the field individually.
For instance: (this list is not complete)
document.querySelectorAll('input, select, textarea');