猫鼬-验证电子邮件语法 [英] Mongoose - validate email syntax

查看:97
本文介绍了猫鼬-验证电子邮件语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于用户的猫鼬模式(UserSchema),我想验证电子邮件是否具有正确的语法.我当前使用的验证如下:

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

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

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?

推荐答案

您可以使用正则表达式.看看这个问题:使用JavaScript验证电子邮件地址吗?

You can use a regex. Take a look at this question: 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.')

这篇关于猫鼬-验证电子邮件语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆