In Mongoose, validating email format is typically done by using regular expressions within the Schema definition. Mongoose provides a validate option that can accept either a validation function or a regular expression, along with an error message.
Here is an example of defining a simple user model in Mongoose and validating the email field format:
jsconst mongoose = require('mongoose'); const Schema = mongoose.Schema; // Define regular expression to validate email format const emailRegex = /^(([^<>()\[\]\.,;:\s@"']+(\.[^<>()\[\]\.,;:\s@"']+)*)|(".+"))@((\[\d{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; // Create a new user schema const userSchema = new Schema({ email: { type: String, required: true, unique: true, // Validate using regular expression validate: { validator: function(email) { return emailRegex.test(email); }, // If validation fails, Mongoose will use this message message: props => `${props.value} is not a valid email address!` } }, // Other field definitions... }); // Create model const User = mongoose.model('User', userSchema); // Use model to create a new user instance const user = new User({ email: 'example@domain.com', // Other field values... }); // Save user and handle possible validation errors user.save(function(err) { if (err) { // If the email format is incorrect, a validation error will occur console.error('Error occurred:', err.message); } else { console.log('User saved successfully!'); } });
In this example, emailRegex defines the validation rules for the email field, applied through the validate option in userSchema. If the provided email does not match the regular expression rules, Mongoose will throw a validation error when attempting to save the user, along with the error message we defined.
Note that this regular expression serves as a basic validation rule for email addresses; the actual rules for email addresses are more intricate, and this regex does not cover all valid email address formats. In practice, you may need to use a more complex regular expression or third-party libraries for more accurate email address validation.