'Two digits after dot with JavaScript onkeypress event in textbox

I have a textbox on my page. I have a JavaScript that the user just write numbers and dots in the textbox. But unfortunately that's not enough. The user must be limited if it puts a dot then it just can write digits after. Are not there validation controls or ajax tool kit, or do I have to do it on the onkeypress event?



Solution 1:[1]

at onblur/onkeyup event of that input:text just check if the entered value match against /\.\d{2}$/ regular expression

Solution 2:[2]

you can try this regexp;

function dotdot(val){
    var rx = /\.\./;
    return rx.test(val);
}

This way you can ensure the user doesn't type a dot after another dot.

Solution 3:[3]

var textbox = document.getElementById("ele_id");
textbox.addEventListener('keyup',function(e){ 
  console.log(textbox.value.match(/^[0-9]*?\.[0-9]{2}$/)); 
}, false);

just tested it in firefox/firebug, you could use "onkeyup" in html or jquery's bind() to make event handler work in IE

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fabrizio Calderan
Solution 2 eyurdakul
Solution 3 Mark Ma