SchemaType.prototype.validate()

Parameters
  • obj «RegExp|Function|Object» validator function, or hash describing options

  • [obj.validator] «Function» validator function. If the validator function returns undefined or a truthy value, validation succeeds. If it returns falsy (except undefined) or throws an error, validation fails.

  • [obj.message] «String|Function» optional error message. If function, should return the error message as a string

  • [obj.propsParameter=false] «Boolean» If true, Mongoose will pass the validator properties object (with the validator function, message, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators rely on positional args, so turning this on may cause unpredictable behavior in external validators.

  • [errorMsg] «String|Function» optional error message. If function, should return the error message as a string

  • [type] «String» optional validator type

Returns:
  • «SchemaType» this

Adds validator(s) for this document path.

Validators always receive the value to validate as their first argument and must return Boolean. Returning false or throwing an error means validation failed.

The error message argument is optional. If not passed, the default generic error message template will be used.

Examples:

  1. // make sure every value is equal to "something"
  2. function validator (val) {
  3. return val == 'something';
  4. }
  5. new Schema({ name: { type: String, validate: validator }});
  6. // with a custom error message
  7. const custom = [validator, 'Uh oh, {PATH} does not equal "something".']
  8. new Schema({ name: { type: String, validate: custom }});
  9. // adding many validators at a time
  10. const many = [
  11. { validator: validator, msg: 'uh oh' }
  12. , { validator: anotherValidator, msg: 'failed' }
  13. ]
  14. new Schema({ name: { type: String, validate: many }});
  15. // or utilizing SchemaType methods directly:
  16. const schema = new Schema({ name: 'string' });
  17. schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');

Error message templates:

From the examples above, you may have noticed that error messages support basic templating. There are a few other template keywords besides {PATH} and {VALUE} too. To find out more, details are available here.

If Mongoose’s built-in error message templating isn’t enough, Mongoose supports setting the message property to a function.

  1. schema.path('name').validate({
  2. validator: function() { return v.length > 5; },
  3. // `errors['name']` will be "name must have length 5, got 'foo'"
  4. message: function(props) {
  5. return `${props.path} must have length 5, got '${props.value}'`;
  6. }
  7. });

To bypass Mongoose’s error messages and just copy the error message that the validator throws, do this:

  1. schema.path('name').validate({
  2. validator: function() { throw new Error('Oops!'); },
  3. // `errors['name']` will be "Oops!"
  4. message: function(props) { return props.reason.message; }
  5. });

Asynchronous validation:

Mongoose supports validators that return a promise. A validator that returns a promise is called an async validator. Async validators run in parallel, and validate() will wait until all async validators have settled.

  1. schema.path('name').validate({
  2. validator: function (value) {
  3. return new Promise(function (resolve, reject) {
  4. resolve(false); // validation failed
  5. });
  6. }
  7. });

You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.

Validation occurs pre('save') or whenever you manually execute document#validate.

If validation fails during pre('save') and no callback was passed to receive the error, an error event will be emitted on your Models associated db connection, passing the validation error object along.

  1. const conn = mongoose.createConnection(..);
  2. conn.on('error', handleError);
  3. const Product = conn.model('Product', yourSchema);
  4. const dvd = new Product(..);
  5. dvd.save(); // emits error on the `conn` above

If you want to handle these errors at the Model level, add an error listener to your Model as shown below.

  1. // registering an error listener on the Model lets us handle errors more locally
  2. Product.on('error', handleError);