Harry Potter
Harry Potter

Reputation: 173

How to validate email in mongoose

Im new to Mongoose...I have a code snippet below. If I want to check what comes after the @ symbol in an email before I save, how would I do that validation?

var user = new User ({
     firstName: String,
     lastName: String,
     email: String,
     regDate: [Date]
});

user.save(function (err) {
  if (err) return handleError(err);
})

Upvotes: 5

Views: 10150

Answers (2)

CodePhobia
CodePhobia

Reputation: 1315

You can use a regex. Take a look at this question: Validate email address in JS?

You can try this

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

Source: Mongoose - validate email syntax

Upvotes: 7

BrettJephson
BrettJephson

Reputation: 416

You can add validation to the schema: http://mongoosejs.com/docs/validation.html

Upvotes: 2

Related Questions