2

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 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, onfocusout doesn't seem to be working. I looked up few more events and onblur is working exactly as I need it to be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.