Guides
Last updated
July 25, 2025

5 Ways to Implement Email Validation in Mongoose

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
email validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Ensuring email addresses are valid in Mongoose is fundamental for clean data. You can find three common ways to handle this validation, each with working code snippets. We'll also examine the shortcomings of these traditional methods and show how Abstract API helps overcome their limitations.

How to Implement Email Validation in Mongoose

Here are four common ways to validate email addresses in Mongoose. Each method includes a description of how it works and a corresponding code snippet for implementation.

Built-in Match Validator

A String path in a schema can take a match option. Mongoose then uses a regular expression to test the input each time the document validates. This method executes synchronously, so it does not require any promise or async setup.

The error message comes from Mongoose’s internal validator. This approach offers a straightforward way to enforce a specific format with zero runtime dependencies.

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    lowercase: true,
    trim: true,
    match: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  }
});

Inline Custom Validator Function

The validate property accepts an object with a validator function and a message. This method provides full control and can be asynchronous if needed, which allows for more complex logic like external API calls.

It also offers a single place to normalize, trim, and compare domains before the document reaches the database. The custom message property allows for specific feedback when validation fails.

const EMAIL_RX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    lowercase: true,
    validate: {
      validator: v => EMAIL_RX.test(v),
      message: p => `${p.value} is not RFC-5322 compliant`
    }
  }
});

Validator.js Integration

This approach integrates the popular third-party library, validator.js. The validator.isEmail() function handles complex validation rules, such as IDNA, UTF-8 local parts, and sub-addressing. This method delegates rule maintenance to the library's team.

It offers more nuance than a simple regular expression and can be easily swapped in or out because it uses the same validate hook.

const validator = require('validator');
const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    lowercase: true,
    validate: {
      validator: v => validator.isEmail(v, { allow_utf8_local_part: false }),
      message: p => `${p.value} fails validator.js isEmail()`
    }
  }
});

Dedicated Schema-Type Plugin

The mongoose-type-email plugin registers "mongoose.SchemaTypes.Email" as a new schema type upon require-time. This approach keeps the schema definition clean, as you just select a different type instead of the addition of validators.

It includes built-in options like "allowBlank" and "correctTld" to reject bare domains. The plugin can be reused across many schemas without code duplication.

require('mongoose-type-email');
const userSchema = new mongoose.Schema({
  email: {
    type: mongoose.SchemaTypes.Email,
    required: true,
    correctTld: true,
    allowBlank: false
  }
});

Challenges of Implementing Email Validation in Mongoose

Traditional Mongoose validation methods primarily check for syntactic correctness. They often fail to confirm an email's actual deliverability or protect against common data quality issues that arise in production.

  • The built-in match validator and other regex-based methods only confirm syntactic correctness. They accept dead mailboxes, disposable domains, and spam-trap addresses because they never verify the email's existence or deliverability.
  • Static regexes in the match validator and custom functions quickly become outdated. They fail to account for new TLDs, Unicode characters, or IDNs, which leads to the rejection of valid emails or the acceptance of invalid ones.
  • The unique: true option is not a validator but an index build process. During concurrent writes or before the index completes, duplicate emails can bypass the check and cause late-stage database errors that require manual translation.
  • Async validators that perform real checks like MX lookups introduce network latency into the save pipeline. This approach adds complexity with retry logic and new failure modes that can stall or even abort document writes.

Validate Emails with Abstract API.
Add reliable email validation to your Mongoose schema to protect your application from bad data.
Get started for free

How Abstract API Handles Email Validation in Mongoose

Abstract API addresses the core weaknesses of traditional methods by perform comprehensive, real-time checks that go beyond simple format validation.

  • It performs RFC-compliant syntax checks and suggests corrections for typos.
  • It confirms a domain has valid MX records and performs a real-time SMTP handshake to ensure the mailbox accepts mail.
  • It detects disposable, free, and role-based email addresses to support custom validation policies.
  • It identifies spam-trap domains before they enter your database.
  • It returns a high-level deliverability status and a quality score for an evidence-based decision.

How to Add Abstract API to Your Dev Environment

Once you know Abstract's capabilities, to add its email validation API to your project is simple.

  • Sign up at Abstract API, create an Email Verification project, and copy the API key.
  • Install the necessary packages.
  • Add your API key to a ".env" file.
  • Create a helper function to call the API.

Sample Email Validation Implementation with Abstract API

You can attach the helper function directly to a Mongoose schema as a custom validator. This code block demonstrates how to integrate the API call into your data model. The validator function checks the API response to ensure the email has a "DELIVERABLE" status and a valid SMTP record before it accepts the data.

If the validation succeeds, the API returns a detailed JSON object. This output gives you an evidence-based decision instead of a simple regex guess. You can use the "quality_score" to gate sign-ups or flag accounts for review, while other flags identify disposable or role-based addresses.

Final Thoughts

Traditional regex validation fails to detect invalid domains, disposable addresses, or spam traps, which allows bad data into your system. Abstract API offers a robust solution with real-time checks for deliverability and infrastructure. Consider an account to get your free API key and reliably validate user emails.

Frequently Asked Questions

What is email validation in Mongoose?

Email validation in Mongoose means adding rules to a schema field so that only properly formatted email addresses are accepted before a document is saved to MongoDB. This can be done with built-in validators like match, inline custom validator functions, or third-party libraries. Each approach checks whether an email looks correct syntactically, but none of them confirm whether the address actually exists or can receive mail.

How do I use the built-in match validator to check email format in Mongoose?

You pass a regex pattern to the match option on the schema field, and Mongoose tests each value against that pattern synchronously before saving. This requires no extra dependencies and is the simplest approach. The downside is that regex-only checks can grow outdated as new TLDs and Unicode characters are introduced, so they are best suited for basic format enforcement rather than full deliverability checks.

When should I use a custom validator function instead of match for email validation in Mongoose?

Use a custom validator when you need logic beyond a single regex (for example, blocking role-based addresses, integrating a third-party library like validator.js, or calling an external API asynchronously). The validate property in Mongoose accepts both a validator function and a custom error message, and it supports async functions that return a promise. This flexibility makes it the right choice any time the match shorthand is too limited.

Does Mongoose email validation confirm that an address can actually receive mail?

No. Built-in Mongoose validators only check syntax, not deliverability. They cannot perform SMTP handshake verification, detect disposable or role-based addresses, or flag spam traps. To validate deliverability you need to call an external service like Abstract's Email Validation API from within an async custom validator, checking the API's deliverability status and SMTP result before allowing the document to be saved.

How does validator.js improve email validation in a Mongoose schema?

The validator.js library handles edge cases that simple regex misses, including IDNA domains, UTF-8 local parts, and sub-addressing formats. You pass validator.isEmail(value) inside a custom validator function on your schema field, so Mongoose calls it automatically on every save. It is a good step up from a hand-rolled regex, but like all local validators it still cannot verify whether the mailbox is active or reachable.

What does the mongoose-type-email plugin add over a custom validator?

The mongoose-type-email plugin registers a dedicated schema type rather than attaching a validator to a standard String field. It ships with options like allowBlank and correctTld, which lets you enforce TLD correctness without writing your own regex. This can keep schema definitions cleaner, though it shares the same fundamental limitation as other local approaches: it validates format only and cannot check whether an address is actually deliverable.

Validate Emails with Abstract API
Don't let bad emails compromise your data. Start validating user signups in your application.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required