Posts

Showing posts with the label Numbers

Allow 2 Decimal Places In

Answer : Instead of step="any" , which allows for any number of decimal places, use step=".01" , which allows up to two decimal places. More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places ^\d*(\.\d{0,2})?$ For an example, I have found solution below to be fairly reliable HTML: <input name="my_field" pattern="^\d*(\.\d{0,2})?$" /> JS / JQuery: $(document).on('keydown', 'input[pattern]', function(e){ var input = $(this); var oldVal = input.val(); var regex = new RegExp(input.attr('pattern'), 'g'); setTimeout(function(){ var newVal = input.val(); if(!regex.test(newVal)){ input.val(oldVal); } }, 0); }); Update setTimeout is not working correctly anymore for this, maybe browsers have changed. Some other async solution will need to be devised...