Display error style with javascript using html 5 validations

Viewed 74

I have a form with HTML validations and I am using JS to add or remove error style.

<form action="" id="addForm">
    <div>
        <label for="name">Name</label>
        <input type="text" id="name" name="name" required minlength="3" />
    </div>
    <button type="submit">Add</button>
</form>
window.onload = handleLoad;

function handleLoad() {
  const form = document.forms.addForm;

  const name = form.name;
  name.onkeyup = function () {
    if (name.checkValidity()) {
      name.classList.remove("error");
    } else {
      name.classList.add("error");
    }
  };
}

In this case the error class gets applied as the user is typing in the field. Is there a way to prevent this?

1 Answers

You are using the onkeyup event, which means the event is triggered every time the user releases a key.

If you want to check the input field only when the user moves to the next field, you could use the onfocusout event.

name.onkeyup = function () {
    if (name.checkValidity()) {
        name.classList.remove("error");
    } else {
        name.classList.add("error");
    }
}

P.S., If you have a small form, you could also implement validation when the submit button is clicked.

Related