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”.

Answer

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

let span = input.nextSiblingelement;
while (span && !span.classList.contains("error")) {
    span = span.nextSiblingElement;
}
if (span) {
    span.textContent = /*...*/;
}

Ideally, though, if you can change the markup, I’d make them children of the same container element instead:

<div>
    <input type="text" id="surname" name="surname" required placeholder="Please enter your Surname" pattern="[A-Za-z]{2,15}" />
    <br/><!-- If this can't be done with CSS for whatever reason -->
    <span class="error" id="e_surname"></span>
</div>

Then you could find it with closest and querySelector, which might give you more flexibility in terms of changing your HTML without changing your JavaScript:

const span = input.closest("div").querySelector(".error");
if (span) {
    span.textContent = /*...*/;
}

You could do it with ids, since you’re using ids on those elements:

const span = document.getElementById("e_" + input.id);
if (span) {
    span.textContent = /*...*/;
}

…but if you can do it structurally, it saves you having to manage lots of id values.

Leave a Reply

Your email address will not be published. Required fields are marked *