简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM