RegEx for validating numbers with commas

I have one text field, it can have values ​​as 1 or 1,2 or 1,225,345,21, i.e. several meanings. But now I want to check this input.

toString().match(/^(([0-9](,)?)*)+$/) 

This is the code I'm using. It only validates, but there is one problem when the user enters the following values:

 inputval:1,22,34,25,645(true) inputval:1,22,34,25,645,(falues) 

When the user enters a comma (,) as the last one, he should throw an error.

Can anyone help me?

+6
source share
2 answers

Just manually enable at least one:

 /^[0-9]+(,[0-9]+)*$/ 
+21
source

Options for Ariel Regex :-)

 /^(([0-9]+)(,(?=[0-9]))?)+$/ 

For , should be followed by a digit (?=[0-9]) .

or

 /^(([0-9]+)(,(?!$))?)+$/ 

For , does not follow the end of the line (?!$) .

 /^(?!,)(,?[0-9]+)+$/ 

We check that the first character is not , (?!,) , And then we put the optional , front of the numbers. This is optional because the first block of numbers does not need it.

+2
source

Source: https://habr.com/ru/post/900364/


All Articles