JSPM

mongoose-validation-error-transform

0.0.6
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 158
  • Score
    100M100P100Q91741F
  • License MIT

Automatically transform Mongoose validation error message(s) to a humanized and readable format

Package Exports

  • mongoose-validation-error-transform

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (mongoose-validation-error-transform) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

mongoose-validation-error-transform

Slack Status NPM version Standard JS Style MIT License

Automatically transform Mongoose validation error message(s) to a humanized and readable format, built for CrocodileJS.

Index

Install

npm install --save mongoose-validation-error-transform

You may also want to use mongoose-beautiful-unique-validation too (see this comment)!

Usage

const mongooseValidationErrorTransform = require('mongoose-validation-error-transform');

mongoose.plugin(mongooseValidationErrorTransform, {

  //
  // these are the default options you can override
  // (you don't need to specify this object otherwise)
  //

  // should we capitalize the first letter of the message?
  capitalize: true,

  // should we convert `full_name` => `Full name`?
  humanize: true,

  // how should we join together multiple validation errors?
  transform: function(messages) {
    return messages.join(', ');
  }

});

If you have a Mongoose schema defined with a required String field full_name, and if there is an error with a missing full_name on a document - then it will automatically rewrite the message of full_name is required to Full name is required.

If there are multiple validation error messages, such as:

  • full_name is required
  • age is not at least (18)

Then it will rewrite the error message to Full name is required, Age is not at least (18).

Of course - by modifying the options mentioned above, you can transform the messages however you'd like.

For example, if you'd like to output a <ul> HTML tag with <li> for each error (but only of course if there's more than one error):

mongoose.plugin(mongooseValidationErrorTransform, {
  transform: function(messages) {
    if (messages.length === 1) return messages[0];
    return `<ul><li>${messages.join('</li><li>')}</li></ul>`;
  }
});

This would output the following for the previous example:

<ul><li>Full name is required</li><li>Age is not at least (18)</li></ul>

License

MIT © Nick Baugh