mongoose-validation-error-transform
v0.0.6
Published
Automatically transform Mongoose validation error message(s) to a humanized and readable format
Downloads
254
Readme
mongoose-validation-error-transform
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