Skip to content

Commit

Permalink
Escapes RegExp chars (mongoose-unique-validator#95)
Browse files Browse the repository at this point in the history
* Escape RegExp chars

* Add tests for regex escaping
  • Loading branch information
matanarbel authored and viveleroi committed Apr 15, 2019
1 parent 08da631 commit c5d1c6e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

Expand Down
10 changes: 10 additions & 0 deletions test/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,5 +232,15 @@ module.exports = {
}, {
email: '[email protected]',
username: 'JohnSmith'
}],

USERS_REGEX: [{
username: 'JohnSmith0',
email: '[email protected]',
password: 'j0hnNYb0i0'
}, {
username: 'JohnSmith',
email: '[email protected]',
password: 'j0hnNYb0i'
}]
};
15 changes: 15 additions & 0 deletions test/tests/validation.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down

0 comments on commit c5d1c6e

Please sign in to comment.