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
- Validation is asynchronously recursive: when you call Model#save, sub-document validation is executed. If an error happens, your Model#save callback receives it
- Mongoose doesn't care about complex error message construction. Errors have type identifiers. For example, "min"is the identifier for the error triggered when a number doesn't meet the minimum value. The path and value that triggered the error can be accessed in theValidationErrorobject
Built in validators
Mongoose has several built in validators.
- All SchemaTypes have the built in required validator.
- Numbers have min and max validators.
- Strings have enum and match validators.
Custom validators
Custom validation is declared by passing a validation function and an error type to your SchemaTypes validate method. Read the API docs for details on custom validators, async validators, and more.
Validation errors
Errors returned after failed validation contain an errors object holding the actual ValidatorErrors. Each ValidatorError has a type and path property providing us with a little more error handling flexibility.
var toySchema = new Schema({
  color: String,
  name: String
});
var Toy = db.model('Toy', toySchema);
Toy.schema.path('color').validate(function (value) {
  return /blue|green|white|red|orange|periwinkel/i.test(value);
}, 'Invalid color');
var toy = new Toy({ color: 'grease'});
toy.save(function (err) {
  // err.errors.color is a ValidatorError object
  
  console.log(err.errors.color.message) // prints 'Validator "Invalid color" failed for path color'
  console.log(String(err.errors.color)) // prints 'Validator "Invalid color" failed for path color'
  console.log(err.errors.color.type) // prints "Invalid color"
  console.log(err.errors.color.path) // prints "color"
  console.log(err.name) // prints "ValidationError"
  console.log(err.message) // prints "Validation failed"
});
After a validation error, the document will also have the same errors property available:
toy.errors.color.message === err.errors.color.message