nicholas
nicholas

Reputation: 14561

Test if SVG path ("d" property) string is valid

Is there a javascript/regex test for SVG path instructions out there?

I'm dynamically generating path instructions (the d property of a <path/> element), and would like to test that the string is valid before rendering the path.

Upvotes: 3

Views: 1787

Answers (1)

John Vandivier
John Vandivier

Reputation: 2426

The regex below will provide some level of confidence. If a string fails this test it is not a valid d value, however I can't guarantee that all values which pass this test are valid d values:

const sValid = `
  M 213.1,6.7
  c -32.4-14.4-73.7,0-88.1,30.6
  C 110.6,4.9,67.5-9.5,36.9,6.7
  C 2.8,22.9-13.4,62.4,13.5,110.9
  C 33.3,145.1,67.5,170.3,125,217
  c 59.3-46.7,93.5-71.9,111.5-106.1
  C 263.4,64.2,247.2,22.9,213.1,6.7
  z
`;

const sOtherValid = 'M213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9';

// true means it is definitely invalid
// false *doesn't* mean it's definitely valid
function isInvalidD(s) {
   const reEverythingAllowed = /[MmZzLlHhVvCcSsQqTtAa0-9-,.\s]/g;

   const bContainsIllegalCharacter = !!s.replace(reEverythingAllowed,'').length;
   const bContainsAdjacentLetters = /[a-zA-Z][a-zA-Z]/.test(s);
   const bInvalidStart = /^[0-9-,.]/.test(s);
   const bInvalidEnd = /.*[-,.]$/.test(s.trim());

   return bContainsIllegalCharacter || bContainsAdjacentLetters || bInvalidStart || bInvalidEnd;
}


console.log(isInvalidD('bro'))

console.log(isInvalidD(sOtherValid))

console.log(isInvalidD('M213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.'))

console.log(isInvalidD('213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9'))

console.log(isInvalidD('MM213.1,6.7c-32.4-14.4-73.7,0-88.1,30.6C110.6,4.9,67.5-9.5,36.9,6.7C2.8,22.9-13.4,62.4,13.5,110.9'))

console.log(isInvalidD(sValid))

console.log(isInvalidD('K213.1,6.7c-32.4-14.4-73.7,0-88'))

The above test is based on W3 SVG spec section 9.3.9.

If you want a more comprehensive validator you can use http://validator.nu. While that service is not a regex, it can validate the whole SVG not just the d value. It also depends which SVG spec you are dealing with. I assume the recent 1.2 spec. Check this answer for more info.

Upvotes: 2

Related Questions