Home > Software engineering >  Javscript strip all but positive numbers and commas and dots from input
Javscript strip all but positive numbers and commas and dots from input

Time:03-13

I have a type="number" input field. On keyup I need to strip all characters (including -) except for 0-9 . and , (I don't care about the order). This proves suprisingly difficult - I haven't found an answer yet.

I got the following:

$input.on('keyup change', () => {
  $input.val($input.val().replace(/[^0-9\,\.]/,''));
});

The regex is from this thread (Rails strip all except numbers commas and decimal points), but it doesn't work - if I type 1. the input vanishes.

CodePudding user response:

It seems at least in some browsers (Edge) the type="number" field value returns sanitized value, which means what you see on screen might be different from what javascript sees (for example value for 99. will be 99 (no dot)).

Also these fields don't allow change cursor position, which means if you replace it's value, cursor will always be at the end.

Because of these limitation, perhaps you'd better off using regular text input and sanitize it manually leaving only characters you want:

test.addEventListener("input", e =>
{
  let start = test.selectionStart;
  //remove invalid characters
  test.value = test.value.replace(/[^0-9,.]/g, (letter, index) =>
  {
    if (index <= start)
      start--;

    return "";
  })
  //remove duplicate , and .
  .replace(/([,.])(.*)[,.]/g, (a, b, c, index) =>
  {
    if (index <= start)
      start -= a.length - b.length - c.length;

    return b c;
  });
  test.selectionStart = test.selectionEnd = start;
});
<input id="test">

CodePudding user response:

Consider using Absolute Value.

$(function() {
  $("#myNumber").on('keyup change', function(event) {
    $(this).val(Math.abs($(this).val()));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="myNumber" min="0" />

  • Related