django
django

Reputation: 2909

javascript Regex verfiy list separated by commas

I need to prepare regex which must verify list separated by commas Requirement is

  1. Check if list is separated by commas
  2. There must be no trailing comma/commas
  3. ,, is not allowed ; there must be word inbetween commas
  4. there must be atleast one comma

JS : https://jsfiddle.net/bababalcksheep/yyw29bj8/4/

//check if list is separated by commas
//There must be no trailing comma/commas
// ,, is not allowed ; there must be word inbetween commas
// there must be atleast one comma

var test = function(STR) {
  return /[-\w\s]+(,[-\w\s]+)*/g.test(STR);
}


//must Pass
console.log('===== PASS ============');
console.log(test('1000,two thousand,3000'));
console.log(test('1000 , 2000 , 3000'));
console.log(test('First Option,2Nd Option, THIRD Option'));

//must fail
console.log('===== FAIL ============');
console.log(test('Single Value'));
console.log(test('1000 ,, 2000 , 3000'));
console.log(test('1000 , 2000 , 3000,'));
console.log(test(',,1000 , 2000 , 3000'));
console.log(test('1000 , 2000 , 3000,,'));

Upvotes: 2

Views: 58

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You should remove /g since you are using RegExp.test(), add anchors ^ and $ (to disallow partial matches) and replace the * with the + quantifier (to require at least one comma):

/^[-\w\s]+(,[-\w\s]+)+$/.test(STR);
 ^                   ^^

See the updated fiddle and a regex demo (I replaced \s with regular spaces for demo purposes).

If you want to avoid validating sequences like ---,----, you can further enhance the regex like:

^\s*\w+(?:\s+\w+)*(?:\s*,\s*\w+(?:\s+\w+)*)+\s*$

See another regex demo and a fiddle.

This regex matches any string with leading/trailing optional spaces (due to ^\s* and \s*$), that starts with a word followed with zero or more spaces + words (with \w+(?:\s+\w+)*) and this can be followed 1 or more times with optional spaces, comma, and a word followed with spaces + words (0 or more times).

Upvotes: 2

Related Questions