Limit digit and decimal point

Allow numbers and decimal only with not more than the given digit and decimal can't exist more than the user given value.

by Carl Angelo Nievarez

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" class="decimal" />

JavaScript

$(function() {
  $('.decimal').on('input', function() {
    this.value = this.value
      .replace(/[^\d.]/g, '')             // numbers and decimals only
      .replace(/(^[\d]{10})[\d]/g, '$1')   // not more than 2 digits at the beginning
      .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
      .replace(/(\.[\d]{2})./g, '$1');    // not more than 4 digits after decimal
  });
});