0
0
MongodbHow-ToBeginner · 4 min read

How to Create Custom Validator in Mongoose: Simple Guide

In Mongoose, you create a custom validator by adding a validate property to your schema field with a function that returns true or false. This function checks if the data meets your custom rule, and you can also provide a custom error message.
📐

Syntax

To create a custom validator in Mongoose, add a validate property to a schema field. This property can be an object with two keys: validator (a function that returns true if valid, false if invalid) and message (a string or function for the error message).

Example parts:

  • validator: function to check the value
  • message: error message shown if validation fails
javascript
fieldName: {
  type: String,
  validate: {
    validator: function(value) {
      // return true if valid, false if invalid
    },
    message: 'Custom error message here'
  }
}
💻

Example

This example shows a schema with a custom validator that checks if a username contains only letters and numbers.

javascript
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    validate: {
      validator: function(v) {
        return /^[a-zA-Z0-9]+$/.test(v); // only letters and numbers
      },
      message: props => `${props.value} is not a valid username! Use only letters and numbers.`
    }
  }
});

const User = mongoose.model('User', userSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  try {
    const user = new User({ username: 'John_Doe' }); // invalid because of underscore
    await user.save();
  } catch (error) {
    console.log(error.message); // shows validation error message
  }

  try {
    const user2 = new User({ username: 'JohnDoe123' }); // valid
    await user2.save();
    console.log('User saved successfully');
  } finally {
    await mongoose.disconnect();
  }
}

run();
Output
User validation failed: username: John_Doe is not a valid username! Use only letters and numbers. User saved successfully
⚠️

Common Pitfalls

Common mistakes when creating custom validators in Mongoose include:

  • Not returning true or false from the validator function, which causes validation to always pass or fail unexpectedly.
  • Using asynchronous code inside the validator without properly handling it (Mongoose supports async validators but requires returning a promise).
  • Forgetting to provide a helpful error message, making debugging harder.
javascript
/* Wrong: validator does not return a boolean */
username: {
  type: String,
  validate: {
    validator: function(v) {
      return /^[a-zA-Z0-9]+$/.test(v); // forgot to return
    },
    message: 'Invalid username'
  }
}

/* Right: validator returns boolean */
username: {
  type: String,
  validate: {
    validator: function(v) {
      return /^[a-zA-Z0-9]+$/.test(v);
    },
    message: 'Invalid username'
  }
}
📊

Quick Reference

Summary tips for custom validators in Mongoose:

  • Use validate with a validator function returning true or false.
  • Provide a clear message for validation errors.
  • For async validation, return a promise or use async function.
  • Test your validators with valid and invalid data.

Key Takeaways

Create custom validators in Mongoose by adding a validate property with a validator function to your schema fields.
Always return true or false from the validator function to indicate valid or invalid data.
Provide a helpful error message to make validation errors clear.
For asynchronous validation, use async functions or return promises.
Test your validators with both valid and invalid inputs to ensure they work correctly.