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?
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'));                  
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With