Manan
Manan

Reputation: 1195

JavaScript Regex - How to check comma separated values are more than three

I am not good with JavaScript Regex, so I need help checking my string for validation.

I am getting these image names separated by comma: Chrysanthemum.jpg,Desert.png,Hydrangeas.gif,Jellyfish.jpg,

Now I want to check with this regex:

What is valid:

Chrysanthemum.jpg,Desert.png,Hydrangeas.gif,Jellyfish.jpg,Koala.jpg,Lighthouse.png,

What is not valid:

1. Chrysanthemum.jpg,Desert.png,Hydrangeas.gif,
2. Chrysanthemum.jpg,Desert.png,
3. Chrysanthemum.jpg,

Validation should only succeed when the amount of comma separated values are more than 3.

Upvotes: 1

Views: 1939

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

The below regex would validates for filename extensions, spaces after the comma except the last one and the comma seperated values are more than 3,

^[A-Z][a-z]+\.(?:jpg|png|gif),(?: [A-Z][a-z]+\.(?:jpg|png|gif),){3,}$

DEMO

If the values are not seperated by comma and space then your regex would be,

^[A-Z][a-z]+\.(?:jpg|png|gif),(?:[A-Z][a-z]+\.(?:jpg|png|gif),){3,}$

DEMO

OR

A much simpler one,

^(?:[A-Z][a-z]+\.(?:jpg|png|gif),){4,}$

DEMO

Upvotes: 1

Ilya Luzyanin
Ilya Luzyanin

Reputation: 8110

Are you sure you need regex for that? Try this:

var str = "Chrysanthemum.jpg, Desert.png, Hydrangeas.gif, Jellyfish.jpg,";
var length = str.split(',').filter(function(item) { return item != ""; }).length;
if (length > 3) {
  ...
}

Upvotes: 0

zx81
zx81

Reputation: 41848

Option 1: Count the Commas Followed by Text

Here is a simple approach:

if (/(?:,\s*\S+){3}/.test(yourString)) {
    // It matches!
} else {
    // Nah, no match...
}

This checks that there are at least three commas followed by optional spaces, then non-space characters.

In the Regex Demo, you can see how this works (there is a match).


Option 2: Check that You Have At Least Four Images

This option checks that you have at least four images.

if (/^\w+\.(?:jpg|png|gif)(?:, \w+\.(?:jpg|png|gif)){3}/.test(yourString)) {
    // It matches!
} else {
    // Nah, no match...
}

See the matches in the Regex Demo.

Upvotes: 1

Related Questions