0

I have an input field I want the input value to be only numbers and decimals nothing more but the problem is that when I type the Unicode characters and letters and semicolons the input value excepts it how do I achieve that.

          let newValue = item.value.replace(new RegExp(/[a-z] && [@!#$%^&*()_+}{}|:,=] /,'ig'), "");
            item.value = newValue;
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
Yyuv Ali
  • 13
  • 6

3 Answers3

2

If you want to only accept number and decimals for your input you can do either of these two ways:

  1. Use input type number.
<input type="number"/>
  1. Use a regex like below, which accept only numbers and decimals:
^-?[0-9]\d*(\.\d+)?$

NOTE: If you want to use the comma (and . in any place) as input also, you can use this one (according to this post):

^-?[0-9][\.\d]*(,\d+)?$
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
1

Update

Validation on input:

var org = '';
document.getElementsByTagName('input')[0].oninput = function(e) {
  var val = document.getElementsByTagName('input')[0].value;
  
  if(val == '' || val.match(/^([0-9]*\.)?[0-9]*$/)) {
    org = val;
  } else {
    val = org;
  }
  
  document.getElementsByTagName('input')[0].value = val;
}
document.getElementsByTagName('input')[0].oninput();
Number here: <input value="1.23" type="text" /><br />
Community
  • 1
  • 1
SirPilan
  • 4,649
  • 2
  • 13
  • 26
0

function scrubInput() {
  let numberInputElem = document.getElementById('numberInput');

  const regex = /[^0-9\.]/
  let newValue = numberInputElem.value.replace(regex, "");
  numberInputElem.value = newValue;
}
<input type="text" id="numberInput" oninput="scrubInput()"/>
tinymothbrain
  • 412
  • 2
  • 6
  • 1
    non-number values like `1.2.3` or `..11..` are accepted. and pasting text inside does not trigger scrubbing – Phu Ngo May 10 '20 at 02:14
  • Hey can you remove if the period is repeating like 1..2 that's not good but instead like this 1.2. – Yyuv Ali May 10 '20 at 07:45