Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
})
like image 881
Harry Potter Avatar asked Dec 21 '15 15:12

Harry Potter


People also ask

What is validation in mongoose?

Validation is defined in the SchemaType. Validation is middleware. Mongoose registers validation as a pre('save') hook on every schema by default. You can disable automatic validation before save by setting the validateBeforeSave option. You can manually run validation using doc.

Does mongoose have built in validation?

Mongoose gives us a set of useful built-in validation rules such: Required validator checks if a property is not empty. Numbers have min and max validators. Strings have enum , match , minlength , and maxlength validators.

What is Mongoose unique validator?

mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.


1 Answers

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

like image 55
CodePhobia Avatar answered Oct 04 '22 11:10

CodePhobia