You are viewing documentation for a beta release that is currently undergoing final testing before its official release. For the latest stable version click here.
Parameter Validation
Validation middleware is used for Actions and Events parameter validation.
In order to perform parameter validation you need to define params property in action definition and create validation schema for the incoming ctx.params.
Example
const { ServiceBroker } = require("moleculer");
const broker = new ServiceBroker({ validator: true// Default is true });
broker.call("say.hello").then(console.log) .catch(err =>console.error(err.message)); // -> throw ValidationError: "The 'name' field is required!"
broker.call("say.hello", { name: 123 }).then(console.log) .catch(err =>console.error(err.message)); // -> throw ValidationError: "The 'name' field must be a string!"
FastestValidator (>= v1.11.0) supports async custom validators, meaning that you can pass metadata for custom validator functions. In Moleculer, the FastestValidator passes the ctx as metadata. It means you can access the current context, service, broker. This allows you to make async calls (e.g calling another service) in custom checker functions. To enable it you must set useNewCustomCheckerFunction to true in moleculer.config.js
const res = await ctx.call("users.isValid", { id: value }); if (res !== true) errors.push({ type: "invalidOwner", field: "owner", actual: value }); return value; } }, }, /* ... */ } }
Events Validation
Event parameter validation is also supported. To enable it, define params in event definition.
Please note that the validation errors are not sent back to the caller, as happens with action errors. Event validation errors are logged but you can also catch them with the global error handler.