davidpm4
davidpm4

Reputation: 582

Mongoose Validation - perform multiple custom validations

I have a basic mongoose Schema:

var userSchema = new Schema({
    userName: {type: String, required: 'Please enter a username'},
    email: {type: String, required: 'Please enter email'},
    password: {type: String, required: 'Please create a password'},
    created: {type: Date, default: Date.now}
});

And I perform a custom validator that calls a small service (in another file) to find if the email address is already in use:

userSchema.path('email').validate(function(value, next) {
    userService.findUser(value, function(err, user) {
        if (err) {
            console.log(err);
            return next(false);
        }
        next(!user);
    });
}, 'Already exists');

Here is the findUser method:

exports.findUser = function(email, next) {
    User.findOne({email: email.toLowerCase()}, function(err, user) {
        next(err, user);
    });
};

My question is: if I would like to use a module like validator to validate whether the input is an email or not, how would I go about doing that? I know I can require the module and do something like validator.isEmail(email) and get a boolean in return, but how can I integrate this with my current setup?

Upvotes: 2

Views: 2200

Answers (2)

venturz909
venturz909

Reputation: 330

The easiest way would be to use a RegEx in the schema to validate if it is a valid email. Then use UserSchema.pre('save' function...) to validate if the email is already in use. This would act as a middleware to be called within the signup method.

var userSchema = new Schema({
    userName: {type: String, required: 'Please enter a username'},
    email: {type: String, required: 'Please enter email'},
    password: {
           type: String, 
           match: [/.+\@.+\..+/, "Please fill a valid email address"], 
           required: 'Please create a password'},
           created: {type: Date, default: Date.now}
});

Upvotes: 0

TM.
TM.

Reputation: 3741

Simplest way is just check it inside validate method. It will return validation error if email is invalid.

var validator = require('validator');

// Validate email address
userSchema
  .path('email')
  .validate(function (value) {

    return validator.isEmail(value);

  }, 'Email is invalid');

And here some suggestion to use constructor to check email for uniqueness:

// Validate that email is not taken
userSchema
  .path('email')
  .validate(function (value, respond) {
    var self = this;

    this.constructor.findOne({email: value}, function (err, user) {
      if (err) {
        return respond(false);
      }

      if (user) {
        if (self.id === user.id) {
          return respond(true);
        }
        return respond(false);
      }
      respond(true);
    });
  }, 'Already exists');

Upvotes: 2

Related Questions