1

I have a text field where I need only 1 and 0 anything else will break my logic code.

How do i possibly restrict any other character from being entered in an input field?

I looked through posts regarding on a somewhat similar subject but they allowed numbers from 0-9 and so on. I tried using the pattern attribute in html but there is no pattern that does this, at least i haven't found it.

I have found this code:

$(function(){
              $('#BinaryInputArea').bind('input', function(){
                $(this).val(function(_, v){
                 return v.replace(/\s+/g, '');
                });
              });
            });

which restricts SPACES from being entered, this uses again patterns that only seem to be known by veterans. I tried adding [2-9] in the .replace section but sadly it was out of the bounds of my logic.

EDIT: I am using a TextArea for input so a regular input pattern:[0-1] wont work

Dice
  • 49
  • 8

2 Answers2

3

You can do this with regular expressions:

var txtInput = document.getElementById("txtInput");

txtInput.addEventListener("keydown", function(evt){
  var regEx = /^(0|1)$/;
  
  // Account for two ways to press 0 and 1 on full-size keyboards
  var key1 = String.fromCharCode(evt.keyCode);
  var key2 = String.fromCharCode(evt.keyCode-48); // Adjustment for the keydown event

  // Test key against regular expression
  if(!regEx.test(key1) && !regEx.test(key2)){
    evt.preventDefault();
  }
});
<form>
  <textarea id="txtInput"></textarea>
  <button>Submit</button>
</form>

Or, you can do this by checking for specific keys being pressed:

var input = document.getElementById("txtInput");

// Do event binding in JavaScript, not in HTML
input.addEventListener("keydown", function(evt){

  // Get the code for the key that was pressed
  var char = evt.keyCode;

  // Is the SHIFT key being held down?
  if(evt.shiftKey){
    // If so, cancel the event
    evt.preventDefault();
  } else {
    // Not the SHIFT key, but if it is 48, 49, 96, 97 
    // (the four ways to get 0 or 1 on a keyboard with a num pad)
    switch (char) {
      case 48:
      case 49:
      case 96:
      case 97:
        break;  // do nothing
      default:
        // Some other key, cancel the event.
        evt.preventDefault();  
        break;
    }
  }
});

// Don't allow pasting into the field
input.addEventListener("paste", function(evt){
  evt.preventDefault();
});
<form>
  <textarea id="txtInput"></textarea>
  <button>Submit</button>
</form>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • The `
    ` will still submit if pattern does not match without `required` attribute set at `` element
    – guest271314 Nov 05 '17 at 01:10
  • @guest271314 Well, the form will submit when no data is entered, but the OP didn't state that the field was required. – Scott Marcus Nov 05 '17 at 01:12
  • @ScottMarcus Hmm, by pressing SHIFT+`+(anyKey) I seem to be able to insert any corresponding character. And i can insert other symbols by copying and pasting them(manually). – Dice Nov 05 '17 at 01:25
  • @Dice What browser are you using (FF by any chance)? And, yes, the answer doesn't address pasting content. I'll update for that scenario. – Scott Marcus Nov 05 '17 at 01:27
  • @Dice What version? I'm running Chrome 62 and it's working just fine. And, I know this code works all the way back to at least v30-ish. – Scott Marcus Nov 05 '17 at 01:29
  • @Dice Silly question, but you are sure you've placed this code in your document AFTER all the HTML has been parsed - - just before the `

    `, right? Does your console show any errors?

    – Scott Marcus Nov 05 '17 at 01:33
  • `@ScottMarcus Version 62.0.3202.62 hmm, yes i did what you said yet i can still exploit this by pressing SHIFT + ´ + anykey – Dice Nov 05 '17 at 01:35
  • @ScottMarcus on the other hand i cant copy and paste no more – Dice Nov 05 '17 at 01:41
  • @Dice Does your Console show any errors? What happens when you try running the code snippet in my answer? – Scott Marcus Nov 05 '17 at 01:49
  • @ScottMarcus I can do the same exploit in the code snippet, no errors in console that i can see of.. – Dice Nov 05 '17 at 02:34
  • @Dice Can’t explain that. I know this code is standard and have used it for years without issues. – Scott Marcus Nov 05 '17 at 02:45
  • @ScottMarcus I guess one would have to secure it thoroughly.. Right now the most workable answer is the answer i checked. – Dice Nov 05 '17 at 16:08
  • I don't see how you can say that. That answer permits any key and then removes it, showing the key for a moment because it works with the value already present in the field. The first of my two answers avoids that. – Scott Marcus Nov 05 '17 at 16:11
1

If you want to do it using javascript you can do something like:

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 49'>
</input>

EDIT: Ok, my first post just pretended to give an example of how it could be done on a line. But you need to have into account a lot of details like allowing the user to use the keyboard keys, copy and paste events, delete characters, etc. You should also control if the user paste a non-valid value.

So here is a more detailed example:

In one line:

<input name="number" onkeyup="if (/[^0-1]|^0+(?!$)/g.test(this.value)) this.value = this.value.replace(/[^0-1]|^0+(?!$)/g,'')">

A jquery example:

$(document).ready(function() {
  $('input.validateBinary').keyup(function(event) {
    var regEx = /^(0|1)$/;
    if (!regEx.test(this.value)) {
      this.value = this.value.replace(/[^0-1]|^0+(?!$)/g, '');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="validateBinary" />
  • HTML event attributes, such as `onkeypress`, `onclick`, etc. should not be used. That's how we did event binding 20 years ago. **[Here's why](https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991)** you should not use them today. Also, you haven't considered that there are two ways to enter `0` and `1` on full sized keyboards. – Scott Marcus Nov 05 '17 at 01:13
  • Also, `charCode` is **[non-standard and deprecated](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/charCode)** in favor of `keyCode`. – Scott Marcus Nov 05 '17 at 01:23
  • Oh, and `input` doesn't get a closing tag. – Scott Marcus Nov 05 '17 at 01:55