出于某种原因,validate: [ isEmail, 'Invalid email.'] 不能很好地配合 validate() 测试。
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.
}
但是 mongoose 4.x(它也可能适用于旧版本)还有其他与单元测试配合使用的替代选项。
单一验证器:
email: {
type: String,
validate: {
validator: function(value) {
return value === 'correct@example.com';
},
message: 'Invalid email.',
},
},
多个验证器:
email: {
type: String,
validate: [
{ validator: function(value) { return value === 'handsome@example.com'; }, msg: 'Email is not handsome.' },
{ validator: function(value) { return value === 'awesome@example.com'; }, msg: 'Email is not awesome.' },
],
},
如何验证电子邮件:
我的建议:留给已经投入数百小时构建适当验证工具的专家。 (也已在here 中回答)
npm install --save-dev validator
import { isEmail } from 'validator';
...
validate: { validator: isEmail , message: 'Invalid email.' }