Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!