Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda