Search code examples
javascripthtmlvalidation

How do I properly pass through a parameter using .addEventListener?


I'm building a registration form with alphabetical input only, and I'm trying to simplify my code so that if a non-alphabetical character is entered into either fname or lname, it'd output the error message below.

Currently, the error message appears prior to inputting and remains even when I input alphabetical characters. My guess is that I get the error message before inputting anything because the addEventListener function immediately calls fname or lname with no input (thus the subsequent error), but why doesn't this resolve itself once you fill in the inputs with alphabetical characters?

I know how to code this with two different ABCvalidate functions (i.e. removing the parameters and using fname.value and lname.value, respectively, but I'm looking for a simplistic solution that works within one ABCvalidate function.

// First Name & Last Name Validation

let ABC = /^[A-Za-z]+$/;

let fname = document.getElementById("fname");
fname.addEventListener('input', ABCvalidate(fname));
let lname = document.getElementById("lname");
lname.addEventListener('input', ABCvalidate(lname));

function ABCvalidate(name) {
  const errorElement = document.getElementById("CSerror");
  if (!ABC.test(name.value)) {
    errorElement.innerHTML =
      "No spaces, numbers, or special characters allowed";
  } else {
    errorElement.innerHTML = "";
  }
}

21


Solution

  • You could just use anonymous functions:

    Variant A

    let fname = document.getElementById("fname");
    let lname = document.getElementById("lname");
    
    fname.addEventListener('input', function() {
        ABCvalidate(this);
    });
    
    lname.addEventListener('input', function() {
        ABCvalidate(this);
    });
    

    Instead of using fname and lname as parameter, you can just use this in this context as this will refer back to the element the event listener was added to.

    Variant B

    The so-called arrow function expression user Jaromanda X already mentioned is also possible. You can't use the this keyword, but you can - as slebetman mentioned - pass event and therefore use event.target instead:

    let fname = document.getElementById("fname");
    let lname = document.getElementById("lname");
    
    fname.addEventListener('input', (event) => ABCvalidate(event.target));
    lname.addEventListener('input', (event) => ABCvalidate(event.target));