Skip to content

Commit

Permalink
Fix string truncate with max ref. Closes #1826
Browse files Browse the repository at this point in the history
  • Loading branch information
hueniverse committed Jun 16, 2019
1 parent 18b5fe6 commit 9685eb1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/types/string/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const Hoek = require('@hapi/hoek');
const Any = require('../any');
const Common = require('../../common');
const JoiDate = require('../date');
const Ref = require('../../ref');

const Ip = require('./ip');
const Uri = require('./uri');
Expand Down Expand Up @@ -120,7 +121,15 @@ internals.String = class extends Any {
if (this._flags.truncate) {
const rule = this._uniqueRules.get('max');
if (rule) {
value = value.slice(0, rule.args.limit); // BUG - issue 1826
let limit = rule.args.limit;
if (Ref.isRef(limit)) {
limit = limit.resolve(value, state, prefs);
if (!internals.checkLimit(limit)) {
return { value, errors: this.createError('number.ref', limit, { ref: rule.args.limit }, state, prefs) };
}
}

value = value.slice(0, limit);
}
}

Expand Down Expand Up @@ -464,7 +473,7 @@ internals.String = class extends Any {

const refs = {
limit: {
assert: (value) => Number.isSafeInteger(value) && value >= 0,
assert: internals.checkLimit,
code: 'string.ref',
message: 'limit must be a positive integer or reference'
}
Expand Down Expand Up @@ -731,4 +740,10 @@ internals.String.prototype._rules = {
internals.String.prototype.uuid = internals.String.prototype.guid;


internals.checkLimit = function (limit) {

return Number.isSafeInteger(limit) && limit >= 0;
};


module.exports = new internals.String();
24 changes: 24 additions & 0 deletions test/types/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -4494,6 +4494,30 @@ describe('string', () => {
[' abcdef ', true, null, 'aabcd']
]);
});

it('truncates a string (ref)', () => {

const ref = Joi.ref('b');
const schema = Joi.object({
a: Joi.string().max(ref).truncate(),
b: Joi.number()
});

Helper.validate(schema, [
[{ a: 'abc', b: 4 }, true, null, { a: 'abc', b: 4 }],
[{ a: 'abcde', b: 2 }, true, null, { a: 'ab', b: 2 }],
[{ a: 'abcdef', b: 5 }, true, null, { a: 'abcde', b: 5 }],
[{ a: 'abc' }, false, null, {
message: '"a" references "ref:b" which is not a number',
details: [{
message: '"a" references "ref:b" which is not a number',
path: ['a'],
type: 'number.ref',
context: { key: 'a', label: 'a', ref }
}]
}]
]);
});
});

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

0 comments on commit 9685eb1

Please sign in to comment.