Search code examples
javascripthtmlvalidation

Why isn't my alphabetical input validation working?


I'm building a registration form with alphabetical input only, and regardless of whether I input an alphabetical or special character, my error message still appears. As it stands, I thought my code would search through the value in fname, and if it doesn't match the characters in ABC, then it should return FALSE and create my error message at the bottom (except my error message appears even when I input an alphabetical character, which I thought should output TRUE and not execute the IF statement).

What am I doing wrong?

// First Name & Last Name Validation

let fname = document.getElementById("fname");
fname.addEventListener("keypress", ABCvalidate);
let ABC = /^[A-Za-z]+$/;

function ABCvalidate() {
  if (!ABC.test(fname.value)) {
    document.getElementById("CSerror").innerHTML =
      "No spaces or special characters allowed";
  }
}

1 2 3


Solution

  • Some of the issues i see

    1. The keypress event is deprecated
    2. it is fired when a key is pressed down, so before the character has been added to the value of the input element (and thus on first press the value is empty, and the test is false)
    3. you never clear the error message if the value is corrected

    You can use the input event which will also handle copy/pastes in to the input element.

    // First Name & Last Name Validation
    
    let fname = document.getElementById("fname");
    fname.addEventListener("input", ABCvalidate);
    let ABC = /^[A-Za-z]+$/;
    
    function ABCvalidate() {
      const errorElement = document.getElementById("CSerror");
      if (!ABC.test(fname.value)) {
        errorElement.innerHTML = "No spaces or special characters allowed";
      } else {
        errorElement.innerHTML = '';
      }
    }
    <input id="fname" />
    <div id="CSerror"></div>