Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to restrict 'n' digits before and after decimal point

I need a regex for restrict 10 digits before decimal and 2 digits after decimal point. i have tried with this

if (!(/^\d{1,10}(\.$|\.\d{1,2}$|$)/).test(value)) {
  event.preventDefault();
  event.stopPropagation();
}
<input id="input" type="number" />

It is working fine for input type text.But it is not working for type number.

Working Fiddle

Please help me on this

like image 741
Gopesh Avatar asked Jan 06 '23 22:01

Gopesh


2 Answers

To restrict Decimal places before and after decimal this should work:

function ValidateDecimalInputs(e) {

    var beforeDecimal =3;
    var afterDecimal = 2;
   
    $('#'+e.id).on('input', function () {
        this.value = this.value
          .replace(/[^\d.]/g, '')            
          .replace(new RegExp("(^[\\d]{" + beforeDecimal + "})[\\d]", "g"), '$1') 
          .replace(/(\..*)\./g, '$1')         
          .replace(new RegExp("(\\.[\\d]{" + afterDecimal + "}).", "g"), '$1');   
    });
    }
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id = "textBox" onclick="ValidateDecimalInputs(this)"/>
like image 195
deepeshb Avatar answered Jan 08 '23 11:01

deepeshb


This should work.

if(! (/^[0-9]{10}\.[0-9]{2}$/).test(1234567890.12)) {
}

Just use this regex /^[0-9]{10}\.[0-9]{2}$/ in your code to verify if value is 10 digits before decimal and 2 after.

like image 35
phreakv6 Avatar answered Jan 08 '23 13:01

phreakv6