From 77012b2cbcec24290b6c3aa34f91f2d33a882e9f Mon Sep 17 00:00:00 2001 From: Youngrok Kim Date: Sat, 23 Jun 2018 20:12:56 +0900 Subject: [PATCH] Add enabled flag to string.trim() resolves #1525 --- lib/types/string/index.js | 26 +++++++++++++++++--------- test/types/string.js | 12 ++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/lib/types/string/index.js b/lib/types/string/index.js index 071271e97..f40eb35a3 100755 --- a/lib/types/string/index.js +++ b/lib/types/string/index.js @@ -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; } diff --git a/test/types/string.js b/test/types/string.js index ec91ac3aa..de0f3397c 100644 --- a/test/types/string.js +++ b/test/types/string.js @@ -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();