1

I want to accept only 0 and 1 in input field and add spaces after every 4 digits. With the following I can add spaces but it accepts all digits. How can I restrict it to only 0 and 1 instead of all digits? I'm having difficulty in the pattern.

document.getElementById('num').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/[^\d]/g, '').replace(/(.{4})/g, '$1 ').trim();
});

Demo: https://jsfiddle.net/5rvfgpzo/

Jay.
  • 191
  • 12

1 Answers1

2

You can try this :

document.getElementById('num').addEventListener('input', function (e) {

  e.target.value = e.target.value.replace(/[^0-1]/g, '').replace(/(.{4})/g, '$1 ').trim();
});
input {
  width: 200px;
  padding: 5px;
}
<label for="num">num</label>
<input id="num" type="text" min="0" max="1" name="num" maxlength="14" />
sanjay
  • 514
  • 2
  • 5
  • 14