VISHWANATH T S
VISHWANATH T S

Reputation: 73

How to validate uniqueness of Email ID in Node JS

I'm trying to validate the uniqueness of the Email ID, when a user enters the duplicate email ID it should show the warning.

Is there any way to get the desired output?

I've tried the below condition, but it won't show the warning in the browser.

 email: {
        type: String,
        unique : true 
    }
The below snippet belongs to "employee.model.js" File.

const mongoose = require('mongoose');

var employeeSchema = new mongoose.Schema({
    fullName: {
        type: String,
        required: 'This field is required.'
    },
    email: {
        type: String,
        unique : true 
    },
    mobile: {
        type: String
    },
    city: {
        type: String
    }
});

mongoose.model('Employee', employeeSchema);

The below code snippet belongs to "employeeController.js" File

const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Employee = mongoose.model('Employee');

router.get('/', (req, res) => {
    res.render("employee/addOrEdit", {
        viewTitle: "Insert Employee"
    });
});

router.post('/', (req, res) => {
    if (req.body._id == '')
        insertRecord(req, res);
        else
        updateRecord(req, res);
});


function insertRecord(req, res) {
    var employee = new Employee();
    employee.fullName = req.body.fullName;
    employee.email = req.body.email;
    employee.mobile = req.body.mobile;
    employee.city = req.body.city;
    employee.save((err, doc) => {
        if (!err)
            res.redirect('employee/list');
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("employee/addOrEdit", {
                    viewTitle: "Insert Employee",
                    employee: req.body
                });
            }
            else
                console.log('Error during record insertion : ' + err);
        }
    });
}

function handleValidationError(err, body) {
    for (field in err.errors) {
        switch (err.errors[field].path) {
            case 'fullName':
                body['fullNameError'] = err.errors[field].message;
                break;
            case 'email':
                body['emailError'] = err.errors[field].message;
                break;
            default:
                break;
        }
    }
}

module.exports = router;

Upvotes: 3

Views: 3353

Answers (1)

Imran Abdalla
Imran Abdalla

Reputation: 115

I suggest dividing your folder structure to

  • Routes (Where all your routes are included)
  • Middle-wares (Where all your Validation are made)
  • Controllers (Where execute the whole function)

let's say we want to validate for a unique Email every time the user is signing up

Our routes folder will contain userRoute.js

router.post(
  '/signup',
  users_validation.validateRegister, // calling validation middle-ware 
  userController.createUser  // calling user controller 
);

In our users_Validation.js file we validate user input using express-validator

/ validate our user inputs for registration
exports.validateRegister = [
  body('fullName').isLength({
    min: 2,
  }),
  body('email').isEmail().withMessage("isn't vaild").trim().escape(),
  body('phone')
    .isNumeric()
    .withMessage('Phone must be numberic value')
    .trim()
    .escape(),

  // after we validate the inputs we check for errors
  //if there are any. just throw them to the user
  // if no errors, call next, for the next middleware
  (req, res, next) => {
    const errors = validationResult(req);

    // check if the validation passes, if not
    // return a json respond with an error message
    if (!errors.isEmpty()) {
      let field = errors.errors[0].param;
      let message = errors.errors[0].msg;
      let errorMessage = field + ' ' + message;

      res.status(400).json({
        message: errorMessage,
        errors: errors,
      });
    } else {
      next();
    }
  },
];

The Next() function will call our Controller createUser.js

exports.createUser = (req, res) => {
  User.findOne({ email: req.body.email }, (err, userWithSameEmail) => {
    if (err) {
      res.status(400).json({
        message: 'Error getting email try gain',
      });
    } else if (userWithSameEmail) {
      res.status(400).json({ message: 'This email is taken' });
    } else {
      const newUser = new User({
        fullName: req.body.fullName,
        email: req.body.email,
        phone: req.body.phone,
      });
      newUser
        .save()
        .then((user) => {
          res.json(user);
        })
        .catch((err) => {
          res.status(400).json({
            message: 'Error registering',
            err,
          });
        });
    }
  });
};

I hope this will do your job, but I strongly recommend using Firebase Authentication for handling your user Authentication, it will make your work much easier than writing the whole logic by your self.

Upvotes: 3

Related Questions