Check for numeric value with optional commas javascript

5.1k Views Asked by At

I need to check a value if it is numeric and optionally contains commas.

I tried

var input=3433;
var pattern=/^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$/;
pattern.test(input);

but it always gave me false;

I don't want to use $.isNumeric as it does not check for commas.

3

There are 3 best solutions below

0
On BEST ANSWER

Your sample var input is not matched by your regex because of the dot.
You could do:

var input=3433;
var pattern=/^[1-9]\d{0,2}(\.?\d{3})*(,\d+)?$/;
//    the dot is optional  __^
pattern.test(input);

This regex will match:

  • 123
  • 1234
  • 1.234
  • 123,45
  • 1234,567
  • 1.234,56
  • 1.234.567,89
1
On

Assuming you're using the comma as a thousands separator, the easiest way to do this is to just remove the commas when converting:

var num = +str.replace(/,/g, '');
if (!isNaN(num)) {
    // It's a valid number
}

If your locale uses . as the thousands separator and , as a decimal point (as your regex seems to suggest), since JavaScript always uses them the other way around, we have more to change in the string first:

var num = +str.replace(/\./g, '').replace(/,/g, ".");
if (!isNaN(num)) {
    // It's a valid number
}
0
On

I must process in different ways strings and string-numbers. So I must test if a string is a string-number (not a valid number), using the locale convention.

My rude solution is:

var num = +str.replace(/\./g, '').replace(/,/g, '');
if (!isNaN(num))...

This works with USA, EUR locales. The control about 'valid number' is done after, car I wanna send detailed WARNING/ERROR messages to user.