Skip to content

Commit

Permalink
Add enabled flag to string.trim()
Browse files Browse the repository at this point in the history
resolves #1525
  • Loading branch information
rokoroku committed Jun 23, 2018
1 parent 8eefd0d commit 77012b2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
26 changes: 17 additions & 9 deletions lib/types/string/index.js
Expand Up @@ -529,20 +529,28 @@ internals.String = class extends Any {
return obj;
}

trim() {
trim(enabled) {

const obj = this._test('trim', undefined, function (value, state, options) {
enabled = enabled === undefined ? true : !!enabled;
let obj;
if (enabled) {
obj = this._test('trim', undefined, function (value, state, options) {

if (options.convert ||
value === value.trim()) {
if (options.convert ||
value === value.trim()) {

return value;
}
return value;
}

return this.createError('string.trim', { value }, state, options);
});
return this.createError('string.trim', { value }, state, options);
});
}
else {
obj = this.clone();
obj._tests = obj._tests.filter((test) => test.name !== 'trim');
}

obj._flags.trim = true;
obj._flags.trim = enabled;
return obj;
}

Expand Down
12 changes: 12 additions & 0 deletions test/types/string.js
Expand Up @@ -1531,6 +1531,18 @@ describe('string', () => {
], { convert: false });
});

it('disable existing trim flag when passing enabled: false', () => {

const schema = Joi.string().trim().trim(false);
Helper.validateOptions(schema, [
[' something', true],
['something ', true],
['something\n', true],
['some thing', true],
['something', true]
], { convert: false });
});

it('removes leading and trailing whitespace before validation', async () => {

const schema = Joi.string().trim();
Expand Down

0 comments on commit 77012b2

Please sign in to comment.