Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - validate email syntax

I have a mongoose schema for users (UserSchema) and I'd like to validate whether the email has the right syntax. The validation that I currently use is the following:

UserSchema.path('email').validate(function (email) {   return email.length }, 'The e-mail field cannot be empty.') 

However, this only checks if the field is empty or not, and not for the syntax.

Does something already exist that I could re-use or would I have to come up with my own method and call that inside the validate function?

like image 424
Tamas Avatar asked Aug 02 '13 16:08

Tamas


People also ask

How do I validate an email address with regex?

With that in mind, to generally validate an email address in JavaScript via Regular Expressions, we translate the rough sketch into a RegExp : let regex = new RegExp('[a-z0-9]+@[a-z]+\.

What is validate in Mongoose schema?

Validation is defined in the Schema. Validation occurs when a document attempts to be saved, after defaults have been applied. Mongoose doesn't care about complex error message construction. Errors have type identifiers.

Does mongoose have built in validation?

Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max 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.


2 Answers

you could also use the match or the validate property for validation in the schema

example

var validateEmail = function(email) {     var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;     return re.test(email) };  var EmailSchema = new Schema({     email: {         type: String,         trim: true,         lowercase: true,         unique: true,         required: 'Email address is required',         validate: [validateEmail, 'Please fill a valid email address'],         match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please fill a valid email address']     } }); 
like image 117
ramon22 Avatar answered Sep 20 '22 01:09

ramon22


I use validator for my input sanitation, and it can be used in a pretty cool way.

Install it, and then use it like so:

import { isEmail } from 'validator'; // ...   const EmailSchema = new Schema({     email: {          //... other setup         validate: [ isEmail, 'invalid email' ]     } }); 

works a treat, and reads nicely.

like image 34
Kris Selbekk Avatar answered Sep 18 '22 01:09

Kris Selbekk