Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mongoose for Application Development

You're reading from  Mongoose for Application Development

Product type Book
Published in Aug 2013
Publisher Packt
ISBN-13 9781782168195
Pages 142 pages
Edition 1st Edition
Languages
Author (1):
Simon Holmes Simon Holmes
Profile icon Simon Holmes

Table of Contents (18) Chapters

Mongoose for Application Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Introducing Mongoose to the Technology Stack Establishing a Database Connection Schemas and Models Interacting with Data – an Introduction Interacting with Data – Creation Interacting with Data – Reading, Querying, and Finding Interacting with Data – Updating Interacting with Data – Deleting Validating Data Complex Schemas Plugins – Re-using Code Index

Doing it your way – create custom validation


Mongoose offers a number of different ways to create custom validators.

Single function – no custom error message

If you only need one piece of validation for a given data item, you can simply specify a function and return true if the validation is passed, and false if it fails.

For example, if we want our usernames to be at least five characters long, we can create a function like the following:

var lengthValidator = function(val) {
  if (val && val.length >= 5){
    return true;
  }
  return false;
};

The function is then referenced in our schema using the validate key:

name: {type: String, required: true, validate: lengthValidator }

This is a very quick and easy way of adding custom validation. It is fine if you just want to check if its okay or not okay as it is reported as an error, but in the error collection the error type comes through as undefined.

Returning a custom error message

If you want a bit more feedback and granularity to your...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}