Validation of <input> with javascript

Asked

Viewed 71 times

-2

I would like to do an inline validation on an input. I want that if the user type something other than 0 or 1, a message appears warning that only 0’s and 1’s are allowed.

Here’s what I’ve tried:

let valor = document.getElementById("binNumber");

valor.addEventListener('keypress', function(e) {
  let conteudo = document.getElementById("binNumber").value
  let splited = conteudo.split("")
  for (let i = 0; i < valor.length; i++) {
    if (splited[i] != 1 || splited[i] != 0) {
      alert("erro")
    }
  }
})
<div>
  <label for="binNumber">Binary:</label>
  <input id="binNumber">
  <label for="decNumber">Decimal</label>
  <input id="decNumber"><br>
  <button>Convert</button>
</div>

I can’t seem to figure this out. You do not need to give me the solution by hand. I appreciate if you give me a direction. The rest I unroll!

Thanks in advance!

1 answer

3

your code has small errors:

  1. no for vc have to do the interaction by splited and not by value
  2. in your if you have to ask for the value in alpha in cases "1" and "0"
  3. the IF operator must be &&( and ).

with this we hit your code, but there is a small concept error, when you make addeventlistener he will run his callback before assigning the value in the element, IE, in the first click the content variable will be empty, and when you click a wrong value it will only validate in the next keypress, you can simply take the parameter of addeventlistener’s Function and ask for the e.key, to know more see Keyboardevent, because it comes by the function parameter, follow doc link: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent follows below the code, you can improve the code making the inputado value does not enter the field.

let valor = document.getElementById("binNumber");

valor.addEventListener('keypress', function(e){

    if(e.key != "1" && e.key != "0"){
      alert("erro")
    }
})

hope I’ve helped.

  • Perfect! Thank you so much! I tested the code, and it worked great. Your comment was super. I didn’t understand everything yet, but it was to delve into what you told me, and try to understand the step-by-step. I will study what you gave me, so I can understand and do in the next! VLW Thiago!

  • Relax, I’m glad I could help!

Browser other questions tagged

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