mongoose schema email code example

Example 1: mongoose schema email type

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

Example 2: email validation in mongoose

import { isEmail } from 'validator';
// ... 

const EmailSchema = new Schema({
    email: { 
        //... other setup
        validate: [ isEmail, 'invalid email' ]
    }
});