diff --git a/README.md b/README.md index 0c9679f2e..e8b7aedd9 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,7 @@ Sanitizer | Description **toDate(input)** | convert the input string to a date, or `null` if the input is not a date. **toFloat(input)** | convert the input string to a float, or `NaN` if the input is not a float. **toInt(input [, radix])** | convert the input string to an integer, or `NaN` if the input is not an integer. +**toString(input)** | convert the input to a string. `null`, `undefined` and `NaN` are converted to an empty string, and objects are converted using their own `toString` method. **trim(input [, chars])** | trim characters (whitespace by default) from both sides of the input. **unescape(input)** | replace HTML encoded entities with `<`, `>`, `&`, `'`, `"`, `` ` ``, `\` and `/`. **whitelist(input, chars)** | remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `whitelist(input, '\\[\\]')`. diff --git a/src/index.js b/src/index.js index 3700cbd6c..5e2cd78a7 100644 --- a/src/index.js +++ b/src/index.js @@ -123,6 +123,7 @@ import blacklist from './lib/blacklist'; import isWhitelisted from './lib/isWhitelisted'; import normalizeEmail from './lib/normalizeEmail'; +import toString from './lib/util/toString'; import isSlug from './lib/isSlug'; import isLicensePlate from './lib/isLicensePlate'; diff --git a/test/exports.test.js b/test/exports.test.js index a5f458f05..283b11540 100644 --- a/test/exports.test.js +++ b/test/exports.test.js @@ -24,6 +24,14 @@ describe('Exports', () => { assert.strictEqual(typeof validator.toFloat, 'function'); }); + it('should export toString and not inherit Object.prototype.toString', () => { + assert.notStrictEqual(validator.toString, Object.prototype.toString); + assert.strictEqual(validator.toString('test'), 'test'); + assert.strictEqual(validator.toString(123), '123'); + assert.strictEqual(validator.toString(null), ''); + assert.strictEqual(validator.toString(undefined), ''); + }); + it('should export the version number', () => { /* eslint-disable global-require */ assert.strictEqual( diff --git a/test/sanitizers.test.js b/test/sanitizers.test.js index e36ba48d3..5f6454afb 100644 --- a/test/sanitizers.test.js +++ b/test/sanitizers.test.js @@ -153,6 +153,18 @@ describe('Sanitizers', () => { }); }); + it('should convert inputs to strings', () => { + test({ + sanitizer: 'toString', + expect: { + foo: 'foo', + '': '', + 123: '123', + ' bar ': ' bar ', + }, + }); + }); + it('should escape HTML', () => { test({ sanitizer: 'escape',