Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex validate string with comma-separated

I'm using JavaScript, I need to accept only string or string with comma-separated if there has more string.

My code is as follows

const text = 'AB1234567';
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/);

My code test is as follows

// first test
const text = 'AB1234567'; // output: 'AB1234567'
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good.

// second test
const text = 'AB1234567, '; // output: 'AB1234567, '
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, but I dont need this.

// third test
const text = 'AB1234567, AB1234568'; // output: 'AB1234567, AB1234568'
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, I need this.

// fourth test
const text = 'AB1234567, AB1234568, '; // output: 'AB1234567, AB1234568, '
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, but I dont need this.

How can I accept only the correct value?

Correct values is first test and third test

like image 602
iAxel Avatar asked Apr 21 '26 05:04

iAxel


1 Answers

Your regex will accept strings that end with a comma and a space, which apparently you don't want. So, let's make the regex enforce that the string doesn't end that way:

text.match(/^([A-Za-z]{2}[0-9]{7},\s)*[A-Za-z]{2}[0-9]{7}$/);
like image 154
Andrew Merrill Avatar answered Apr 22 '26 19:04

Andrew Merrill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!