55
votes

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?

8

8 Answers

118
votes

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

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.

22
votes

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

The validator dosn't play well with mongoose to get rid of the warning set isAsync to false

const validator = require('validator');

email:{
type:String,
validate:{
      validator: validator.isEmail,
      message: '{VALUE} is not a valid email',
      isAsync: false
    }
}
10
votes

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.

4
votes

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 === '[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 here as well)

npm install --save-dev validator

import { isEmail } from 'validator';
...
validate: { validator: isEmail , message: 'Invalid email.' }
4
votes

Email type for schemas - mongoose-type-email

var mongoose = require('mongoose');
require('mongoose-type-email');

var UserSchema = new mongoose.Schema({
    email: mongoose.SchemaTypes.Email
});

Possible Reference:

1
votes
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'
    }
  }