I have some client-side validation against a text box, which only allows numbers up to two decimal places with no other input.
This script was a basis for entering numeric values only, however it needs to be adapted so it can take a decimal point followed by only up to two decimal places.
I’ve tried things such as /[^\d].\d{0,2}, but then the replacement call wouldn’t work, and I’ve got no idea how to do it.
Code
<script type='text/JavaScript'> function valid(f) { if (!/^\d*$/.test(f.value)) { f.value = f.value.replace(/[^\d]/g,''); alert('Invalid number'); } } </script>
Note
I need to match an empty string. If an empty string is provided and the form is submitted, the value defaults back to zero.
The . character has special meaning in RegEx so needs escaping.
This matches 123.45, 123.4, 123 and .2, .24 but not emtpy string, 123., 123.456