6

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

3
  • Why not just inputValue.replace(/[^0-9.,]+)/,''); Commented Jul 31, 2014 at 17:03
  • in ES6 I believe you can use Number.isFloat(inputValue) || Number.isInteger(inputValue) Commented Jul 31, 2014 at 17:06
  • I'm not. My fiddle only works with numbers, but I can't get the decimal in there. I can't figure out the RegEx string to allow it. Commented Jul 31, 2014 at 17:08

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.