JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.
August 4, 2011

Validating YAML-style Tag Strings with Javascript

This has an admittedly very specific use-case, but recently I needed to validate strings matching the following formats:

[apples, oranges]
[[apples, oranges]]
[apples, oranges, [peaches, grapes]]

The bracket nesting is important as it will later be parsed by a YAML parser to generate nested arrays of strings

[
  "apples",
  "oranges",
  [
    "peaches",
    "grapes"
  ]
]

and then converted to SQL conditions

... WHERE tag1.tag ILIKE "apples" OR tag2.tag ILIKE "oranges" OR (tag3.tag ILIKE "peaches" AND tag4.tag ILIKE "grapes")

The user needed to be prompted as they were entering the strings in this unique format to let them know whether or not their string was valid.

validateTagFormat = function(string){
  var b = 0;
  for (i=0; i<string.length; i++) {
    var c = string[i];
    switch (c) {
      case '[':
        b++;
        break;
      case ']':
        b--;  
        break; 
    }
  }

  if (b != 0) return false;
  if (string.indexOf('[') > string.indexOf(',') && string.indexOf(',') != -1) return false;
  if (string.indexOf(',') > -1 && string.indexOf('[') == -1) return false;
  if (/\]\s*[^\],]/.test(string)) return false;

  string = string.replace(/[\[\]]/g, '');
  string = string.replace(/,\s*/g, ', ');

  return /^[a-zA-Z0\-\ ]+((\,\ )[a-zA-Z0\-\ ]+)*$/.test(string);   
};

This jsFiddle instance shows this in action.

Tags: javascript code yaml parser validation