Regex Replace all but Numbers and Decimal Place

Xthralls

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.

yosefrow

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Regex to replace decimal and integer strings with numbers

Regex to replace everything except numbers and a decimal point

Regex for all decimal numbers to match English format

Regex - replace all the 11 digit numbers with link

Regex to replace all non numbers but allow a '+' prefix

JavaScript regex to replace all numbers with percentage sign

Is there a way to replace all unwanted numbers and characters with regex?

Regex replace 'whole' decimal numbers not followed by a certain string

C++ regex_replace to clean concatenated decimal numbers

Find dot and replace with coma on decimal numbers (Notepad++ RegEx)

JS regex replace single digit number in string but not in decimal numbers

Regex to replace decimal number and all period in currency format

Regex for Numbers with Optional Decimal

Regex to detect numbers but not decimal

Regex - I need to replace all digits but specific 3 digits numbers

Regex: Replace all except numbers, specific characters and specific words

Capturing numbers that are larger than 1 decimal place

How to drop decimal place on numbers in a JSON array?

Only accept numbers with one decimal place

Match numbers (decimal and whole) with Regex

Regex for numbers including decimal and slashes

Regex replace decimal numbers that do not belong to a hex color value and are not followed by a certain string

Use regex to find any number with a decimal place

Java match on one regex decimal place

Javascript Decimal Place Restriction To Specific Number With Regex

regex two place decimal with . valid at end

DecimalFormat - keep all decimal numbers

Showing all decimal numbers in C

Replace all the hex by decimal in a file