5

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);
})
Harry Potter
  • 173
  • 3
  • 12

2 Answers2

7

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

Community
  • 1
  • 1
CodePhobia
  • 1,315
  • 10
  • 19
  • Im not sure I understand this. Do I need an if statement? so if the email ends in "@google.com", for example, it will save as admin and if the email is just valid "something@something.com" it will save as a user – Harry Potter Dec 21 '15 at 15:46
  • 1
    in that case, inside the validate 1. After verifying the email is valid 2. Branch an if-else, one for checking the admin mail endings other for inserting the average joe. :) – CodePhobia Dec 21 '15 at 15:50
  • If above code doesn't works try to remove .text for email parameter, so it become like 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.') ____ – azwar_akbar Jan 18 '19 at 10:42
2

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

BrettJephson
  • 416
  • 5
  • 13