When validating a form with querySelectorAll – how to select the appropriate span to output the error

I am adding event listeners to input fields with querySelectorAll and I am wondering how to display an error messagge in the appropriate span, when a form "error" occurs.

I have found this post, which looks promising, but I don’t know if it’s do-able with my current aproach.

const inputs = document.querySelectorAll("input");
inputs.forEach(function(input){
    input.addEventListener("blur", function (){
        if(input.validity.valueMissing){
            //select appropriate span
        }
    })
})
<input type="text" id="surname" name="surname" required placeholder="Please enter your Surname" pattern="[A-Za-z]{2,15}" />
</br>
<span class="error" id="e_surname"></span>
</br>

Not related – Additionally I would like to display different error messagges for e-mail/telephone/etc input fields… I don’t know if I can roll all of that in one "function".

19 thoughts on “When validating a form with querySelectorAll – how to select the appropriate span to output the error”

  1. Since your span is a sibling of your input, you can scan forward to it:

    let span = input.nextSiblingelement;
    while (span && span.tagName !== "SPAN") {
        span = span.nextSiblingElement;
    }
    if (span) {
        span.textContent = /*...*/;
    }
    
    Reply

Leave a Comment