Mongoose - validate email syntax
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Mongoose validates email syntax through the validate option on a schema field. The most common approach is a regex validator defined inline, but you can also use a custom validator function or a third-party library like validator. Mongoose does not include a built-in email validator, so you always need to provide the logic yourself.
This article covers regex validation, custom validators, async validators, the validator library approach, and the practical decisions that determine which approach fits your project.
Schema-Level Regex Validation
The simplest and most common pattern is a regex check defined directly in the schema.
A few things worth noting here.
The lowercase: true option normalizes the email before validation runs. This prevents duplicates caused by case differences like [email protected] vs [email protected].
The trim: true option strips leading and trailing whitespace, which is a common source of validation failures when data comes from form inputs.
The unique: true option creates a MongoDB unique index, but it is not a Mongoose validator. If uniqueness is violated, MongoDB throws a duplicate key error (code 11000), not a Mongoose ValidationError. Handle both.
Understanding the Regex Pattern
The pattern /^[^\s@]+@[^\s@]+\.[^\s@]+$/ is deliberately simple. Here is what each part matches.
| Component | Matches | Purpose |
^ | Start of string | Anchors the match |
[^\s@]+ | One or more characters that are not whitespace or @ | Local part (before the @) |
@ | Literal @ sign | Required separator |
[^\s@]+ | One or more characters that are not whitespace or @ | Domain name |
\. | Literal dot | Separates domain from TLD |
[^\s@]+ | One or more characters that are not whitespace or @ | Top-level domain |
$ | End of string | Anchors the match |
This pattern accepts [email protected] and rejects obvious non-emails like @missing.com, no-at-sign, and spaces [email protected]. It intentionally does not try to implement the full RFC 5322 spec because a "perfect" email regex is thousands of characters long and provides marginal practical benefit. In production, the real validation happens when you send a confirmation email.
Custom Validator Functions
For reusable validation logic, extract the validator into a standalone function.
The array syntax [validatorFn, errorMessage] is a shorthand for the object form. Both are equivalent.
You can extend the custom validator with additional business rules.
This is a practical pattern for SaaS applications that want to reject disposable email addresses at registration time.
Using the validator Library
The validator npm package provides a battle-tested isEmail function that handles edge cases better than most hand-written regexes.
validator.isEmail supports options for stricter or more permissive checking.
| Approach | Pros | Cons |
| Inline regex | No dependency, easy to read | Limited coverage of edge cases |
| Custom function | Reusable, can add business rules | Still relies on your own regex |
validator.isEmail | Well-tested, configurable, maintained | Adds a dependency |
For most projects, validator.isEmail is the right choice. The library is small, widely used, and maintained.
Async Validators
Mongoose supports async validators for checks that require database or external service calls. A common use case is checking whether an email already exists before save.
Note that the isAsync: true option is deprecated in Mongoose 5+. Mongoose now detects async validators automatically when the function returns a Promise. Simply use async/await or return a Promise.
Handling Validation Errors
When validation fails, Mongoose throws a ValidationError with details about each failing field.
Output.
For uniqueness violations, the error comes from MongoDB, not Mongoose validation.
Handle both error types in your API layer to return consistent responses to clients.
Combining Multiple Validators
A single field can have multiple validators by using an array.
Mongoose runs all validators and collects all failures into the ValidationError, so the client gets a complete list of problems in a single response.
Common Pitfalls
Treating unique: true as a validator. It creates a MongoDB index, not a Mongoose validation rule. It does not produce a ValidationError. It produces a MongoDB duplicate key error with code 11000. Handle both types.
Writing a regex that rejects valid emails. Addresses like [email protected], [email protected], and "quoted local"@example.com are all valid per RFC 5322. Overly strict regexes reject real users. When in doubt, keep the regex simple and validate by sending a confirmation email.
Forgetting lowercase and trim. Without normalization, [email protected] and [email protected] are treated as different values by the unique index, causing duplicates.
Using isAsync: true on Mongoose 5+. This option is deprecated. Return a Promise or use async/await instead.
Not indexing the email field. The unique: true option creates an index, but if you also query by email for login, ensure the index is in place. Without it, every login triggers a collection scan.
Summary
- Mongoose does not include a built-in email validator. You must provide one through
validate. - The simplest approach is an inline regex like
/^[^\s@]+@[^\s@]+\.[^\s@]+$/. - For production applications, the
validatorlibrary'sisEmailfunction is more robust and well-maintained. - Use
lowercase: trueandtrim: trueto normalize email values before validation. - Handle both
ValidationError(from Mongoose) and duplicate key errors (from MongoDB, code 11000) in your error handling. - Async validators detect promises automatically in Mongoose 5+. Do not use
isAsync: true.
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.