Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for JavaScript validation of comma separated numbers

I have one text box and it can have values like 1 or 1,2 or 1,225,345,21 (i.e., multiple values). But now I want to validate this input.

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

This is the code I'm using. It is validating correct only, but one problem when the user enters values like this:

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

When the user enters a comma (,) at the end, it should throw an error.

Can any one help me please?

like image 889
pradeep kumar Avatar asked Oct 30 '11 09:10

pradeep kumar


2 Answers

Just manually include at least one:

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

let regex = /[0-9]+(,[0-9]+)*/g

console.log('1231232,12323123,122323',regex.test('1231232,12323123,122323')); 
console.log('1,22,34,25,645,',regex.test('1,22,34,25,645,'));
console.log('1',regex.test('1'));                  
like image 132
Ariel Avatar answered Oct 05 '22 23:10

Ariel


Variants on the Ariel's Regex :-)

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

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

Or

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

The , must not be followed by the end of the string (?!$).

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

We check that the first character isn't a , (?!,) and then we put the optional , before the digits. It's optional because the first block of digits doesn't need it.

like image 43
xanatos Avatar answered Oct 05 '22 23:10

xanatos