Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex - sanitize string with whitelist

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

like image 791
Scott Avatar asked Oct 20 '22 04:10

Scott


1 Answers

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.

like image 68
anubhava Avatar answered Oct 23 '22 03:10

anubhava