aurelius aurelius - 7 months ago 55
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 ".".

^[-]?[0-9]+([\.][0-9]{0,9})?$


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:

-12345678901234567890123456789.123456789

123456789012345678901234567890.1

-1.123456789

Answer

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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input>

Regex explanation

Regular expression visualization