Tamas
Tamas

Reputation: 11214

Mongoose - validate email syntax

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?

Upvotes: 64

Views: 136884

Answers (10)

elias-soykat
elias-soykat

Reputation: 139

const mongoose = require("mongoose");

const validateEmail = function(email) {
  const regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  return regex.test(email);
};

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, "Please enter your email"],
    validate: [validateEmail, "Please enter a valid email"],
    unique: true,
  },


module.exports = mongoose.model("User", userSchema);

Upvotes: 2

Sandeep Amarnath
Sandeep Amarnath

Reputation: 6916

  • Use npm package called validator that can give you a bunch of validations out of the box and not only for just the email

  • Use validate property in your schema on the email field that takes in two nested properties - validator (Function) and a message. The validator function is where we use the npm package we installed in our first step

Code

npm install validator

Define schema

const mongoose = require('mongoose')
const validatorPackage = require('validator')

const UserSchema = new mongoose.Schema({
      .......
    
      email: {
        type: String,
        unique: true,
        required: [true, 'Email address is required'],
        validate: {
          validator: validatorPackage.isEmail,
          message: 'Please provide a valid email',
        },
      },
      .......
      
})

const model = mongoose.model('User', UserSchema)

module.exports = model

Upvotes: 0

o.z
o.z

Reputation: 1156

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:

Upvotes: 4

Isaac S. Weaver
Isaac S. Weaver

Reputation: 135

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.

Upvotes: 13

Eka Cipta
Eka Cipta

Reputation: 229

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

Upvotes: 0

Patryk Acu&#241;a
Patryk Acu&#241;a

Reputation: 140

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

Upvotes: 14

zurfyx
zurfyx

Reputation: 32777

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

Upvotes: 5

ramon22
ramon22

Reputation: 3628

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

Upvotes: 138

Kris Selbekk
Kris Selbekk

Reputation: 7654

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.

Upvotes: 94

dannyp32
dannyp32

Reputation: 494

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

Upvotes: 24

Related Questions