Xthralls
Xthralls

Reputation: 45

Regex Replace all but Numbers and Decimal Place

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.

Upvotes: 1

Views: 3158

Answers (1)

yosefrow
yosefrow

Reputation: 2268

As you can see in the working fiddle I have created here https://jsfiddle.net/yosefrow/Lscyn8q3/2/

in the processInput function

var processInput = function(inputValue) {
  let outputValue = parseFloat(inputValue.replace(/[^.0-9]/g, ''));
  console.log("outputValue: " +  outputValue);
  updateDOM(inputValue, outputValue);
};

The line

outputValue = parseFloat(inputValue.replace(/[^.0-9]/g, ''));

in your implementation compares to

inputValue = $(this).val();
outputValue = parseFloat(inputValue.replace(/[^.0-9]/g, ''));

This means that if your code is not working, it may be related to some pre-processing that is happening before or during the definition of the inputValue

Maybe something is stripping the periods out? Maybe your javascript code is being processed in some way to affect the period in your regular expression?

Edit

Based on the code added, I can safely say that the function stripping out the periods is the parseFloat that is called on each key press. Because parseFloat does not view 1234. as a valid number, it strips it out even though the replace method does not.

You need to add a function that

  1. skips periods
  2. sanity checks double periods. e.g. reduce double periods .. to one period .
  3. ignore periods if a period already exists in the string somewhere

You may also wish to incorporate existing validation methods such as

https://jqueryvalidation.org/number-method/

A simpler approach to validation on the fly might be to simply do a search replace on each key press without using parseFloat.

e.g.

// replace middle non float chars
outputValue = inputValue.replace(/[^.0-9]/g, '')
// replace non number start
outputValue = inputValue.replace(/^[^0-9]/g, '')
// replace double dots
outputValue = inputValue.replace(/\.\./g, '.')

keep in mind it wont resolve ending period '.' so maybe parsefloat before submission

Upvotes: 1

Related Questions