For some reason validate: [ isEmail, 'Invalid email.']
doesn't play well with validate()
tests.
const user = new User({ email: 'invalid' });
try {
const isValid = await user.validate();
} catch(error) {
expect(error.errors.email).to.exist; // ... it never gets to that point.
}
But mongoose 4.x (it might work for older versions too) has other alternative options which work hand in hand with Unit tests.
Single validator:
email: {
type: String,
validate: {
validator: function(value) {
return value === '[email protected]';
},
message: 'Invalid email.',
},
},
Multiple validators:
email: {
type: String,
validate: [
{ validator: function(value) { return value === '[email protected]'; }, msg: 'Email is not handsome.' },
{ validator: function(value) { return value === '[email protected]'; }, msg: 'Email is not awesome.' },
],
},
How to validate email:
My recommendation: Leave that to experts who have invested hundreds of hours into building proper validation tools. (already answered in here as well)
npm install --save-dev validator
import { isEmail } from 'validator';
...
validate: { validator: isEmail , message: 'Invalid email.' }