乐闻世界logo
搜索文章和话题

How to validate email in mongoose

3个答案

1
2
3

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:

js
const 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.

2024年6月29日 12:07 回复

您还可以使用matchvalidate属性在模式中进行验证

例子

shell
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'] } });
2024年6月29日 12:07 回复

您可以使用正则表达式。看看这个问题:Validate email address in JavaScript?

我过去用过这个。

shell
UserSchema.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.')
2024年6月29日 12:07 回复

你的答案