From c5d1c6e9742c4647420a460214ccfb848525deda Mon Sep 17 00:00:00 2001 From: matanarbel Date: Tue, 16 Apr 2019 02:58:15 +0300 Subject: [PATCH] Escapes RegExp chars (#95) * Escape RegExp chars * Add tests for regex escaping --- index.js | 2 ++ test/helpers.js | 10 ++++++++++ test/tests/validation.spec.js | 15 +++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/index.js b/index.js index 1a857da..d8d93cf 100644 --- a/index.js +++ b/index.js @@ -70,6 +70,8 @@ module.exports = function(schema, options) { // Wrap with case-insensitivity if (get(path, 'options.uniqueCaseInsensitive') || indexOptions.uniqueCaseInsensitive) { + // Escapse RegExp chars + pathValue = pathValue.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); pathValue = new RegExp('^' + pathValue + '$', 'i'); } diff --git a/test/helpers.js b/test/helpers.js index 0fe234e..a153e73 100644 --- a/test/helpers.js +++ b/test/helpers.js @@ -232,5 +232,15 @@ module.exports = { }, { email: 'john.smith2000@gmail.com', username: 'JohnSmith' + }], + + USERS_REGEX: [{ + username: 'JohnSmith0', + email: 'john0smith@gmail.com', + password: 'j0hnNYb0i0' + }, { + username: 'JohnSmith', + email: 'john.smith@gmail.com', + password: 'j0hnNYb0i' }] }; diff --git a/test/tests/validation.spec.js b/test/tests/validation.spec.js index fa3e254..0f661d7 100644 --- a/test/tests/validation.spec.js +++ b/test/tests/validation.spec.js @@ -22,6 +22,21 @@ module.exports = function(mongoose) { promise.catch(done); }); + it('allow unique records with regex wildcards', function(done) { + var User = mongoose.model('User', helpers.createUserCaseInsensitiveSchema().plugin(uniqueValidator)); + + // Save the first user + var promise = new User(helpers.USERS_REGEX[0]).save(); + promise.then(function() { + // Try saving a unique user with email that has a regex wildcard + new User(helpers.USERS_REGEX[1]).save().catch(done).then(function(res) { + expect(res.email).to.equal(helpers.USERS_REGEX[1].email); + done(); + }); + }); + promise.catch(done); + }); + it('throws error for single index violation', function(done) { var User = mongoose.model('User', helpers.createUserSchema().plugin(uniqueValidator));