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

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

  1. First off I would like to say excellent blog! I had a quick question that I’d like to ask if you do not mind.
    I was curious to know how you center yourself and clear your
    mind prior to writing. I have had difficulty clearing my thoughts in getting my thoughts out.
    I truly do enjoy writing but it just seems like the first 10 to 15 minutes
    are lost simply just trying to figure out how to begin. Any ideas or hints?

    Appreciate it! https://herreramedical.org/hydroxychloroquine

    Reply

Leave a Comment