Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fredemagi's avatar

Regex for comma separated string in validation

Hello,

I'm making an application in which I need some validation. The user is able to enter multiple zipcodes in a text input, separated by comma.

Legal input: 0000 0000,1214

Illegal use_of_letters_and_underscores_etc 000 00 0 0000, 1214 0000, 1214, 0000,1214,

I can't quite figure it out. I have tried:

regex:/^[0-9]{4}+(,[0-9]+)$/

Any help is appreciated!

0 likes
4 replies
Tray2's avatar

I think a bigger list on what is legal and what is not is in order here.

fredemagi's avatar

Thank you for your reply.

I think it easier to descript correct input maybe:

I want zipcodes (of length == 4 digits) in a comma separated list. If only 1 zipcode is given, 4 numbers is a valid input like 1234. If to 2 zipcodes are given, 8 digits separated by comma (without space) between and no end comma is valid like 1324,5214

Etc.

bugsysha's avatar
bugsysha
Best Answer
Level 61

Something like this should work:

^(,?[0-9]{4}){1,}$

Or better this:

^([0-9]{4})(,[0-9]{4}){0,}?$

Or you can shorten:

^\d{4}(,\d{4}){0,}$

Please or to participate in this conversation.