pradeep kumar
pradeep kumar

Reputation: 101

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?

Upvotes: 10

Views: 19186

Answers (2)

Ariel
Ariel

Reputation: 26753

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'));                  

Upvotes: 26

xanatos
xanatos

Reputation: 111860

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.

Upvotes: 5

Related Questions