How do I validate an input as its content changes?

Asked

Viewed 162 times

9

I’d like you to fill in a piece of data input this was being validated, that is, as it was filling a field 'nif' that alerted me an "invalid nif" message until it was correct and did not need to use methods such as the onBlur.

Does anyone know a way to do it?

My code:

function teste(){
  var input = document.getElementById("input").value;

  if(input == 5){
     document.getElementById("5").innerHTML = "sucesso";
  }else{
     document.getElementById("5").innerHTML = "insucesso";
  }
}
<input type="text" id="input" onchange='teste()'>
<h2 id="5"> </h2>

  • Do you have any code developed?

  • https://www.w3schools.com/jsref/event_onkeypress.asp

  • 3

    W3schools is a problem, do not use their link. keypress on MDN will see that the event is discontinued and the advised is to use the event keydown or beforeinput. Not to mention that at MDN teaches to use addEventListener (which is the best way) instead of event in attributes.

3 answers

7


With the event onkeyup you can already do your validation. If you use the onkeydown validation will not be correct as your input will not have the current value pressed.

Take an example:

<html>
<body>

<h1>Input validation test</h1>

<input type="text" onkeyup="myFunction()" id='ipt' placeholder='Sucesso'>

<script>
function myFunction() {
  if (document.getElementById('ipt').value == "Sucesso")
    document.getElementById('ipt').style.backgroundColor = 'green';
  else
    document.getElementById('ipt').style.backgroundColor = 'red';
}
</script>

</body>
</html>

I hope I’ve helped.

7

No need to use Javascript (by the way, you don’t need JS for much stuff), not either jQuery. Use a model simple validation in <input> already gives you the expected result:

input:invalid ~ [data-input-message]::after{
  content: 'Insira o valor 5';
  color: red
}

input:valid ~ [data-input-message]::after{
  content: 'Obrigado :)';
  color: green
}
<input type='text' placeholder='Insira o valor 5' pattern='[5]' required>
<span data-input-message></span>

2

You have another event attribute that calls the function as you type in the field, which is the oninput:

function teste(){
  var input = document.getElementById("input").value;

  if(input == 5){
  document.getElementById("5").innerHTML = "sucesso";

  }else{
    document.getElementById("5").innerHTML = "insucesso";
  }
}
Digite 5:
<br>
<input type="text" id="input" oninput='teste()'>
<h2 id="5"> </h2>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.