In an attempt to do client-side validation on a form, I'm trying to replace all characters in a specific input except for numbers and decimals. I'm not concerned over multiple decimal points as I'm using parseFloat on the string.
While troubleshooting, I came across this question here, in which the recommended answer is the same regex pattern I am using. Regex to replace everything except numbers and a decimal point
While the below pattern works fine for validating numbers, each time I attempt to enter a decimal, it gets stripped out with all other non-numerical characters.
tempVal = parseFloat($(this).val().replace(/[^.0-9]/g, ''));
I want to be able to enter both numbers and decimals into the input box without having the decimals stripped out. As I said, it's the same exact pattern used in the other question above, but does not seem to get the desired result. Any guidance is appreciated.
Update:
Although this is similar to the other question I mentioned (and linked to) above, and while the solution to that question seems to be the same as the code I've used, the resulting value will allow only numbers, but still strips out decimals.
Here is the full JQuery code:
$('#input1, #input2').on('keyup', function() {
if (ignoreBackDelete()) {
return;
}
tempVal = parseFloat($(this).val().replace(/[^.0-9]/g, ''));
if (tempVal.length < 1) {
$(this).val('');
} else {
$(this).val(tempVal);
}
});
And just to show that the ignoreBackDelete() function is not the likely culprit, here's that function's code as well:
function ignoreBackDelete() {
var key = event.keyCode || event.charCode;
if (key == 8 || key == 46) {
return true;
}
return false;
}
I've reviewed my code once again to verify that no other function is triggered when entering values into either #input1 or #input2.
Hopefully, this provides a little more detail to the question.
'asasas2a.322'.replace(/[^.0-9]/g, '')
. All works – SouXin