Skip to content

Commit

Permalink
Merge pull request #1097 from EvgenyOrekhov/964-fix-wrong-value-parsing
Browse files Browse the repository at this point in the history
Fix #964 Joi wrong value parsing
  • Loading branch information
Marsup authored Mar 26, 2017
2 parents 5d484b7 + 670233f commit e349bc8
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ internals.annotate = function (stripColorCodes) {
let ref = obj;
for (let j = 0; j < path.length && ref; ++j) {
const seg = path[j];
if (j + 1 < path.length) {
if (j + 1 < path.length && typeof ref[seg] !== 'string') {
ref = ref[seg];
}
else {
Expand All @@ -279,10 +279,12 @@ internals.annotate = function (stripColorCodes) {
}
else if (lookup[error.path]) {
const replacement = lookup[error.path];
const appended = replacement.replace('_$end$_', `, ${pos}_$end$_`);
ref[appended] = ref[replacement];
lookup[error.path] = appended;
delete ref[replacement];
if (typeof ref[replacement] !== 'string') {
const appended = replacement.replace('_$end$_', `, ${pos}_$end$_`);
ref[appended] = ref[replacement];
lookup[error.path] = appended;
delete ref[replacement];
}
}
else {
ref[`_$miss$_${seg}|${pos}_$end$_`] = '__missing__';
Expand Down
20 changes: 20 additions & 0 deletions test/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -609,5 +609,25 @@ describe('errors', () => {
done();
});
});

it('pinpoints an error in a stringified JSON object', (done) => {

const object = {
a: '{"c":"string"}'
};

const schema = {
a: Joi.object({
b: Joi.string()
})
};

Joi.validate(object, schema, { abortEarly: false }, (err, value) => {

expect(err).to.exist();
expect(err.annotate(true)).to.equal('{\n \"a\" [1]: \"{\\\"c\\\":\\\"string\\\"}\"\n}\n\n[1] \"c\" is not allowed');
done();
});
});
});
});
19 changes: 19 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1760,6 +1760,25 @@ describe('Joi', () => {
}).to.throw('invalid value');
done();
});

it('throws a validation error and not a TypeError when parameter is given as a json string with incorrect property', (done) => {

const schema = {
a: Joi.object({
b: Joi.string()
})
};

const input = {
a: '{"c":"string"}'
};

expect(() => {

Joi.attempt(input, schema);
}).to.throw(/\"c\" is not allowed/);
done();
});
});

describe('compile()', () => {
Expand Down

0 comments on commit e349bc8

Please sign in to comment.