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?
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]+\.
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.
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.
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.
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'] } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With