node.js Mongoose - 验证电子邮件语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18022365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose - validate email syntax
提问by Tamas
I have a mongoose schema for users (UserSchema) and I'd like to validate whether the email has the right syntax. The validation that I currently use is the following:
我有一个用于用户的猫鼬模式(UserSchema),我想验证电子邮件是否具有正确的语法。我目前使用的验证如下:
UserSchema.path('email').validate(function (email) {
return email.length
}, 'The e-mail field cannot be empty.')
However, this only checks if the field is empty or not, and not for the syntax.
但是,这只检查字段是否为空,而不检查语法。
Does something already exist that I could re-use or would I have to come up with my own method and call that inside the validate function?
是否已经存在可以重用的东西,或者我是否必须提出自己的方法并在验证函数中调用它?
采纳答案by dannyp32
You can use a regex. Take a look at this question: Validate email address in JavaScript?
您可以使用正则表达式。看看这个问题:在 JavaScript 中验证电子邮件地址?
I've used this in the past.
我过去用过这个。
UserSchema.path('email').validate(function (email) {
var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailRegex.test(email.text); // Assuming email has a text attribute
}, 'The e-mail field cannot be empty.')
回答by ramon22
you could also use the matchor the validateproperty for validation in the schema
您还可以使用match或validate属性在架构中进行验证
example
例子
var validateEmail = function(email) {
var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(email)
};
var EmailSchema = new Schema({
email: {
type: String,
trim: true,
lowercase: true,
unique: true,
required: 'Email address is required',
validate: [validateEmail, 'Please fill a valid email address'],
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please fill a valid email address']
}
});
回答by Kris Selbekk
I use validatorfor my input sanitation, and it can be used in a pretty cool way.
我将验证器用于我的输入卫生,它可以以一种非常酷的方式使用。
Install it, and then use it like so:
安装它,然后像这样使用它:
import { isEmail } from 'validator';
// ...
const EmailSchema = new Schema({
email: {
//... other setup
validate: [ isEmail, 'invalid email' ]
}
});
works a treat, and reads nicely.
很好用,读起来很好。
回答by Patryk Acu?a
回答by zurfyx
For some reason doesn't play well with validate: [ isEmail, 'Invalid email.']validate()tests.
由于某种原因,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.
}
But mongoose 4.x(it might work for older versions too) has other alternative options which work hand in hand with Unit tests.
但是mongoose 4.x(它也可能适用于旧版本)还有其他与单元测试协同工作的替代选项。
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 hereas well)
我的建议:将其留给投入数百小时构建适当验证工具的专家。(这里也已经回答了)
npm install --save-dev validator
npm install --save-dev validator
import { isEmail } from 'validator';
...
validate: { validator: isEmail , message: 'Invalid email.' }
回答by Isaac S. Weaver
I know this is old, but I don't see this solution so thought I would share:
我知道这很旧,但我没有看到这个解决方案,所以我想分享一下:
const schema = new mongoose.Schema({
email: {
type: String,
trim: true,
lowercase: true,
unique: true,
validate: {
validator: function(v) {
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
},
message: "Please enter a valid email"
},
required: [true, "Email required"]
}
});
You can do this for any type you want to validate and just pass the appropriate regex expression. If you google the type you want to validate and it's related regex expression it's easy to find a solution. This will keep your validations consistent and puts all the code in the schema instead of hanging functions.
您可以对要验证的任何类型执行此操作,只需传递适当的正则表达式即可。如果您在 google 上搜索要验证的类型及其相关的正则表达式,则很容易找到解决方案。这将使您的验证保持一致,并将所有代码放在架构中而不是挂起函数。
回答by o.z
Email type for schemas - mongoose-type-email
模式的电子邮件类型 - mongoose-type-email
var mongoose = require('mongoose');
require('mongoose-type-email');
var UserSchema = new mongoose.Schema({
email: mongoose.SchemaTypes.Email
});
Possible Reference:
可能的参考:
回答by user11195629
email: {
type: String,
match: [/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, `Please fill valid email address`],
validate: {
validator: function() {
return new Promise((res, rej) =>{
User.findOne({email: this.email, _id: {$ne: this._id}})
.then(data => {
if(data) {
res(false)
} else {
res(true)
}
})
.catch(err => {
res(false)
})
})
}, message: 'Email Already Taken'
}
}

