Categories
JavaScript Answers

How to validate email syntax with Mongoose?

Spread the love

Sometimes, we want to validate email syntax with Mongoose.

In this article, we’ll look at how to validate email syntax with Mongoose.

How to validate email syntax with Mongoose?

To validate email syntax with Mongoose, we can set the match property to an array with the regex to validate against and validation error message.

For instance, we write

const validateEmail = (email) => {
  const re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  return re.test(email);
};

const 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",
    ],
  },
});

to create the EmailSchema with the email field.

we add the validate option set to an array with the validateEmail function to validate the email string against the re regex and a validation error message if validateEmail returns false.

Likewise, we set match to an array with the regex to validate against and an validation error message.

We’ll get the message when we call save with an invalid email valuein thesave` callback.

Conclusion

To validate email syntax with Mongoose, we can set the match property to an array with the regex to validate against and validation error message.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *