I have a very basic RegEx problem. I'm trying to sanitize an input field with a whitelist. I'm trying to only allow numbers and a decimal into my field. If a user types an invalid character, I want to strip it out of the input and replace the input with a clean string.
I can get it working with only numbers, but I can't get the decimal into the allowed pool of characters:
var sanitize = function(inputValue) {
var clean = "",
numbersOnly = /[^0-9]/g; // only numbers & a decimal place
if (inputValue) {
if (numbersOnly.test(inputValue)) {
// if test passes, there are bad characters
for (var i = 0; i < inputValue.length; i++) {
clean += (!numbersOnly.test(inputValue.charAt(i))) ? inputValue.charAt(i) : "";
}
if (clean != inputValue) {
makeInputBe(clean);
}
}
}
};
Working fiddle
Rather than looping your input character by character and validating each character you can do this for basic sanitizing operation:
var s = '123abc.48@#'
s = s.replace(/[^\d.]+/g, '');
//=> 123.48
PS: This will not check if there are more than 1 decimal points in the input (not sure if that is the requirement.
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