Skip to content

Commit

Permalink
Validator: Fail for stray ampersand characters
Browse files Browse the repository at this point in the history
Fixes #214
  • Loading branch information
orgads committed Dec 22, 2019
1 parent 156d02f commit a703c1a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
17 changes: 17 additions & 0 deletions spec/validator_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,23 @@ attribute2="attribute2"
var result = validator.validate(xmlData).err;
expect(result).toEqual(expected);
});

it('should validate value with ampersand', function () {
const error = {
InvalidChar: "char '&' is not expected."
};
validate('<rootNode>jekyll &amp; hyde</rootNode>');
validate('<rootNode>jekyll &#123; hyde</rootNode>');
validate('<rootNode>jekyll &#x1945abcdef; hyde</rootNode>');
validate('<rootNode>jekyll &#x1ah; hyde</rootNode>', error);
validate('<rootNode>jekyll &#1a; hyde</rootNode>', error);
validate('<rootNode>jekyll &#123 hyde</rootNode>', error);
validate('<rootNode>jekyll &#1abcd hyde</rootNode>', error);
validate('<rootNode>jekyll & hyde</rootNode>', error);
validate('<rootNode>jekyll &aa</rootNode>', error);
validate('<rootNode>jekyll &abcdefghij1234567890;</rootNode>');
validate('<rootNode>jekyll &abcdefghij1234567890a;</rootNode>', error); // limit to 20 chars
});
});

describe("should not validate XML documents with multiple root nodes", () => {
Expand Down
36 changes: 36 additions & 0 deletions src/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ exports.validate = function (xmlData, options) {
} else {
break;
}
} else if (xmlData[i] === '&') {
const afterAmp = validateAmpersand(xmlData, i);
if (afterAmp == -1)
return getErrorObject('InvalidChar', `char '&' is not expected.`, getLineNumberForPosition(xmlData, i));
i = afterAmp;
}
} //end of reading tag text value
if (xmlData[i] === '<') {
Expand Down Expand Up @@ -332,6 +337,37 @@ function validateAttributeString(attrStr, options, regxAttrName) {
return true;
}

function validateAmpersand(xmlData, i) {
// https://www.w3.org/TR/xml/#dt-charref
i++;
if (xmlData[i] === ';')
return -1;
if (xmlData[i] === '#') {
i++;
let re = /\d/;
if (xmlData[i] === 'x') {
i++;
re = /[\da-fA-F]/;
}
for (; i < xmlData.length; i++) {
if (xmlData[i] === ';')
return i;
if (!xmlData[i].match(re))
return -1;
}
return -1;
}
let count = 0;
for (; i < xmlData.length; i++, count++) {
if (xmlData[i].match(/\w/) && count < 20)
continue;
if (xmlData[i] === ';')
break;
return -1;
}
return i;
}

function getErrorObject(code, message, lineNumber) {
return {
err: {
Expand Down

0 comments on commit a703c1a

Please sign in to comment.