aurelius aurelius - 5 months ago 44x
Javascript Question

How to limit total number of digits in a decimal number

I have this regex which validates if a string is a decimal number.
Also this checks if it has at most 9 decimals after ".".


I need to add another check, which limits the total number of digits.

Mention: I need the total number of digits to be less then 38, including the decimal after the point, thus I cannot add the range just to decimals before the point.

valid ex:





You can use regex with positive look ahead assertion /^-?(?=[.\d]{0,39}$)\d{0,38}(\.\d{1,9})?$/

$('input').on('input', function() {
  $(this).css('color', /^-?(?=[.\d]{0,39}$)\d{0,38}(\.\d{1,9})?$/.test(this.value) ? 'green' : 'red');
<script src=""></script>

Regex explanation

Regular expression visualization