ItGo.me Focus on IT Recommend

Home > node.js - Mongoose - validate email syntax

node.js - Mongoose - validate email syntax

2020腾讯云双十一活动,全年最低!!!(领取3500元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1074

【阿里云】双十一活动,全年抄底价,限时3天!(老用户也有),
入口地址https://www.aliyun.com/1111/home

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.

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?

node.js mongodb mongoose
|
  this question
asked Aug 2 '13 at 16:59 Tamas 1,911 6 24 52

 | 

5 Answers
5

---Accepted---Accepted---Accepted---

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

|
  this answer
answered Aug 2 '13 at 17:25 dannyp32 123 9      Awesome! I didn't know about the test() method either. –  Tamas Aug 2 '13 at 17:45      You should define the regex outside of the function for better performance. –  Killah Dec 17 '13 at 5:26 2   This regex fails to validate some valid emails, such as those include the plus sign on the lefthand side. –  Mark Stosberg Mar 21 '14 at 9:21      What exactly is this email.text attribute? –  chovy May 9 '14 at 6:48      @chovy the email.text attribute is basically the email address string. For example "myemail@gmail.com" –  dannyp32 May 12 '14 at 3:46

 | 

you could also use the match or the validate property for validation in the schema

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']
    }
});

|
  this answer
edited Aug 22 '16 at 17:12 answered Jun 13 '14 at 22:48 ramon22 827 14 22

 | 

I use validator for 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.


|
  this answer
edited Feb 10 '16 at 21:36 answered Feb 8 '15 at 16:16 Kris Selbekk 1,486 17 36      for ES5 :) , const validator = require('validator'); validate: [validator.isEmail, 'invalid email'], –  Nazır Dogan Feb 7 at 9:23      const wasn't available in ES5 unfortunately. –  Kris Selbekk Feb 7 at 19:41      aha sorry I was missing to edit to "var" :) –  Nazır Dogan Feb 7 at 21:22

 | 

I made this, which defines a custom field-type complete with email validation.

Recommend:node.js - Mongoose Upsert, Syntax Error

pected token "." at last line. But I cannot understand what is really wrong. I have been looking into it for more than one hour, am I missing a simple concept var seriesSchema = new Schema({ type : {type: Number, default: 1}, featu


|
  this answer
answered Jul 28 '16 at 1:56 konsumer 2,100 17 24

 | 

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 === 'correct@example.com';
    },
    message: 'Invalid email.',
  },
},

Multiple validators:

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.' },
  ],
},

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

|
  this answer
answered Feb 8 at 15:10 zurfyx 5,436 5 30 58

 | 

Recommend:node.js - Validate subdocuments in Mongoose

ields. That's what I have var SubdocumentSchema = new Schema({ foo: { type: String, trim: true, required: true }, bar: { type: String, trim: true, required: true }});var Mai

------splitte line----------------------------