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.
<script type="text/JavaScript">
function valid(f) {
if (!/^\d*$/.test(f.value)) {
f.value = f.value.replace(/[^\d]/g,"");
alert("Invalid number");
}
}
</script>
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.
/^(?:\d*\.\d{1,2}|\d+)$/
This matches 123.45, 123.4, 123 and .2, .24 but not emtpy string, 123., 123.456
.
means in RegEx: any character, you have to put a backslash infront of it. \.
This would be better:
/^\d+(\.\d{0,2})?$/
Parts I included:
+
with *
but then also empty strings would be matched.$
stands for the end of the input.and for the replacing part you should also include the dot
f.value.replace(/[^\d\.]/g, "")
Edit:
If it's for the live validation of inputs, why don't you just either intercept keyevents and test for their validity (by creating the string in memory) or just delete the last character in the field?
Do you really want to do this with a regex?
function valid(f) {
if(isNaN(f)){return false;}
return 100 * f == parseInt(100*f,10);
}
gs: This is very close, but the line
f.value = f.value.replace(/[^\d\.]/g, "");
Doesn't actually appear to work. In fact I lose focus of the text box for some reason. Although perhaps it's my code ;)
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