constraint validation API ValidityState.typeMismatch with using input eventListener not working in hosted applications

Viewed 41

I have created a simple form with the client-side validation using constraint validation API. I'm checking the typeMismatch validity state in the email input element. after testing my application, I found a weird bug in my code.

when I run the index.html file by double-clicking the local hard drive file, it is working perfectly. I mean the input event listener is working perfectly. but if I host this file in a hosting service or if I use live-server it not going to work. (input event listener does not work, but submit button click event listener does work.)

inside my index.html,

 <form>
     <div data-name="email">
        <label for="email">Email</label>
        <input
          type="email"
          name="email"
          id="email"
          required
          placeholder="you@example.com"
          title="required."
        />
     </div>
    <button type="submit" id="submit">submit</button>
  </form> 

inside my main.js file,

const email = document.getElementById("email");
email.addEventListener("input", () => validate(email));

const submit = document.getElementById('submit')
submit.addEventListener("click", () => validate(email))

function validate(element) {
  let isvalid = true;
  const name = element.name;
  const error = document.createElement("span");
  error.setAttribute("aria-live", "polite");
  error.className = "error";
  
  if (element.validity.typeMismatch) {
    error.textContent = `${name} is not in the required syntax. (e.g. you@example.com)`;
  }
  const parent = document.querySelector(`[data-name=${name}]`);
  
  if (parent instanceof HTMLElement) {
    const _error = parent.querySelector(".error");
    if (!_error) parent.append(error);
    else parent.replaceChild(error, _error);
  }
  
  return isvalid;
}
0 Answers
Related