简体   繁体   中英

Display error style with javascript using html 5 validations

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?

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");
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM