Validation

Before we get into the specifics of validation syntax, please keep the following rules in mind:

  • Validation is defined in the SchemaType
  • Validation is an internal piece of middleware
  • Validation occurs when a document attempts to be saved, after defaults have been applied
  • Validators are not run on undefined values. The only exception is the required validator.
  • Validation is asynchronously recursive; when you call Model#save, sub-document validation is executed as well. If an error occurs, your Model#save callback receives it
  • Validation supports complete customization

Built in validators

Mongoose has several built in validators.

Each of the validator links above provide more information about how to enable them as well as customize their associated error messages.

Custom validators

If the built-in validators aren’t enough, validation can be completely tailored to suite your needs.

Custom validation is declared by passing a validation function and coinciding error message to your SchemaTypes validate method. Instructions for how to do so are available in the API docs.

Validation errors

Errors returned after failed validation contain an errors object holding the actual ValidatorErrors. Each ValidatorError has a type, path, and value property providing us with a little more error handling flexibility.

  1. var toySchema = new Schema({
  2. color: String,
  3. name: String
  4. });
  5. var Toy = mongoose.model('Toy', toySchema);
  6. Toy.schema.path('color').validate(function (value) {
  7. return /blue|green|white|red|orange|periwinkle/i.test(value);
  8. }, 'Invalid color');
  9. var toy = new Toy({ color: 'grease'});
  10. toy.save(function (err) {
  11. // err is our ValidationError object
  12. // err.errors.color is a ValidatorError object
  13. console.log(err.errors.color.message) // prints 'Validator "Invalid color" failed for path color with value `grease`'
  14. console.log(String(err.errors.color)) // prints 'Validator "Invalid color" failed for path color with value `grease`'
  15. console.log(err.errors.color.type) // prints "Invalid color"
  16. console.log(err.errors.color.path) // prints "color"
  17. console.log(err.errors.color.value) // prints "grease"
  18. console.log(err.name) // prints "ValidationError"
  19. console.log(err.message) // prints "Validation failed"
  20. });

After a validation error, the document will also have the same errors property available:

  1. toy.errors.color.message === err.errors.color.message

Next Up

Now that we’ve covered validation, let’s take a look at how you might handle advanced validation with Mongoose’s middleware.