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

104
Views
Validate HTML5 input in JS prior to change

It looks like when an input element is initially loaded, its validity is not evaluated right away. For example, if my HTML looks like this...

<input type="text" value="ABC" minlength="5">

In JavaScript it appears that the input is valid and not too short, despite the value attribute being set to a length less than 5. For example:

const input = document.querySelector("input");
console.log(input.validity.valid); // true
console.log(input.validity.tooShort); // false

Only when the user makes a change in the input can we get a true reckoning of the input's validity.

Is there any way to force the input to evaluate its actual validity on load, even if the user has not yet touched the input?

See example: https://jsfiddle.net/t5afujkn/3/

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

0

I guess the reason is your default value is not checked from <input> directly at load as it probably does not trigger a check for the default values.

You can add another check condition in your js as below:

{
    const displayObj = {
       valid: input.validity.valid,
       tooShort: input.validity.tooShort
    };
    if (input.value.length < 5) {
       displayObj.valid = false;
       displayObj.tooShort = true;
       document.querySelector("p").textContent = JSON.stringify(displayObj);
    }
}

or maybe you can also try to put the if condition somewhere outside the button call.

Also I did an update in jsfiddle, not sure if you can see it: https://jsfiddle.net/2Lhp96ct/6/

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!