I want to write a regular expression in which allows
For example:
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]
                Here it is:
/^\d*(?:\.\d{1,2})?$/
Working Demo: http://jsfiddle.net/qd7BL/
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 = "";
        }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With