我有一个mongoose用户模式(UserSchema),我想验证邮箱是否有正确的语法.我目前使用的验证如下:

UserSchema.path('email').validate(function (email) {
  return email.length
}, 'The e-mail field cannot be empty.')

但是,这只判断字段是否为空,而不判断语法.

是否已经存在我可以重复使用的东西,或者我必须想出自己的方法并在validate函数中调用它?

推荐答案

你可以使用正则表达式.看看这个问题:Validate email address in JavaScript?

我以前用过这个.

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.')

Node.js相关问答推荐

monorepo内的NPM包使用不在注册表中的本地包

Jest由于UUID而无法解析测试,即使在Jest中启用ESModule支持后也是如此

Mongoose更新许多不使用数组作为筛选器来更新记录

如何呈现ejs.renderFile中包含的子模板?

获取页面大小为10的所有文章,每篇文章填充一些所需的用户信息

通过 Node js 中的 TBA 执行 netsuite REST upsert 操作出现 401 错误

在 TypeScript 中正确键入 MongoDB find 方法

Amplify 部署的应用程序出现TypeError: handler is not a function错误,但它在本地运行

express 和 mongoose 的新密码不正确

如何通过node下载zip并直接解压zip?

将代码转换为 ES6 Discord.js 的问题

使用 fs.createWriteStream 将数据写入 bigquery (node.js) 时出现模式错误

node Axios 创建全局令牌变量以在单独的变量头中使用

使用`useLocalStorage`和`useDebounce`时如何解决Next.js中的react-hydration-error

如何解决 npm install react-select failure with error : An unknown git error occurred, git@github.com :Permission denied (publickey)

`npm install` 以Killed结尾

在 Passport 策略回调中获取请求对象

使用加密模块的流功能获取文件的哈希(即:没有 hash.update 和 hash.digest)

Express.js中的bodyParser.urlencoded({extended: true }))和bodyParser.json()是什么意思?

使用 Node-sass 缩小 CSS