Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression in JavaScript to allow only numbers with optional 2 decimals

I want to write a regular expression in which allows

  1. backspace
  2. 0-9 digits
  3. optional fractional part with two decimals (no limit on integral part how many digits there can be)

For example:

  • Allowed lists is [12 , 232.0 , 23.(with only dot) , 345.09 , 78.23 , 134.00 , 0.21 , .21 , .02 , .01 .12 ]
  • Not allowed are [12.878 , 34.343.334 , .0003 ]

The use of this regular expression would be like on javascript event

<input type="text"  onKeyPress="validatenumber(event);"   /><br>

My code is

function validatenumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /^[0-9\b]+$/;    // allow only numbers [0-9] 
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

I want to change only this line with the new regex:

var regex = /^[0-9\b]+$/;    // allow only numbers [0-9]
like image 391
user3132930 Avatar asked Jan 18 '14 11:01

user3132930


2 Answers

Here it is:

/^\d*(?:\.\d{1,2})?$/

Working Demo: http://jsfiddle.net/qd7BL/

like image 194
Aziz Shaikh Avatar answered Sep 19 '22 12:09

Aziz Shaikh


find the final solution at least

<input id="txtId" type="text" onkeyup="NumAndTwoDecimals(event , this);"></input>

and the

 function NumAndTwoDecimals(e , field) {
    var val = field.value;
    var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
    var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
    if (re.test(val)) {
        //do something here

    } else {
        val = re1.exec(val);
        if (val) {
            field.value = val[0];
        } else {
            field.value = "";
        }
    }
}
like image 43
user3132930 Avatar answered Sep 20 '22 12:09

user3132930