Search code examples
javascriptformsvalidationuser-input

Maximum two decimal, check on input not working properly


I needed a function in JavaScript that limited the input (form) of a number of a maximum of two decimals. So I found the following online:

function restrict(tis) {
  var prev = tis.getAttribute("data-prev");
  prev = (prev != '') ? prev : '';
  if (Math.round(tis.value * 100) / 100 != tis.value)
    tis.value = prev;
  tis.setAttribute("data-prev", tis.value)
}
<input type="number" name="amount" step="any" oninput="restrict(this);" required>

Honestly It's amazing, the input doesn't allow you more than two decimals, until by chance I entered only zeros, like this "100.000000000", if you enter only zeros as decimals it doesn't limit the field...

Is there anybody that has a fix for this? Thank you very much!

Elliot


Solution

  • I borrowed the regex from the other answer

    function restrict(tis) {
      let prev = tis.getAttribute("data-prev");
      prev = (prev != '') ? prev : '';
      if (!tis.value.match(/^\d*(\.\d{0,2})?$/))
        tis.value = prev;
      tis.setAttribute("data-prev", tis.value)
    }
    <input type="number" name="amount" step="any" oninput="restrict(this);" required>