Skip to content Skip to sidebar Skip to footer

How Can I Make Sure That Whaveter Is In The Text Box Is Only 1's And 0's For Binary?

I have a app right now that converts binary to dec, hex and octal however I would like for it to alert the user if the input is not a binary number and tell them to try again. This

Solution 1:

NOTE! ("1" == 1) will evaluate to true. ("1" === 1) will evaluate false. You are comparing a string to an integer above so it will always fail. (However, I would go with Dave's solution anyway).

Solution 2:

Here's a simple binary validator using Regular Expressions, which is a simpler implementation, especially when you start adding octal and hexadecimal.

var binary = document.getElementById("binary");
binary.addEventListener("input", function(e) {
  var validator = document.getElementById("validator");
  var text = e.target.value;
  if (text.match(/^[0|1]+$/))
    validator.innerHTML = "Valid Binary";
  else
    validator.innerHTML = "Not Valid Binary";
});
<inputid="binary" /><spanid="validator" />

Post a Comment for "How Can I Make Sure That Whaveter Is In The Text Box Is Only 1's And 0's For Binary?"