Mongoose validation: required : false, validate : regex, issues with empty values
I think your regex is failing validation on empty string which should in this case be valid since this field is not required. Why don't you try this regex:
/^$|^\d{10}$/
This will match an empty string or 10 digits.
You may try with a custom validator as they are only triggered when there is a value on a given key because the key selection for custom validation is done via path()
:
var user = new Schema({
// ...
phone : { type: String }, // using default - required:false
// ...
});
// Custom validation
user.path('phone').validate(function (value) {
// Your validation code here, should return bool
}, 'Some error message');
Have a look at this question: Why Mongoose doesn't validate empty document?
This will also effectively prevent the document to be persisted to the DB if validation fails, unless you handle the error accordingly.
BonusTip: Try to approach custom validations in a simplistic way, for example try to avoid loops when possible and avoid using libraries like lodash or underscore for in my experience I've seen that these may have a significant performance cost when working with lots of transactions.