Parameter Validation Middleware with Celebrate

Celebrate makes it easy to accomplish strong parameter validation.

If you’re building a web app with any significant client-side user input, it’s important to validate the existence of certain parameters in PUT and POST requests.

It’s definitely possible to validate these inputs manually inside your controllers; however, celebrate makes it super easy to run automatic validations via express middleware. Celebrate uses the awesome joivalidator under the hood to create schemas and assertions about our data.

An Example

Express middleware normally takes the form of:

(req, res, next) => {

// your custom code here

// move on to the next middleware
next();
};

With celebrate, we’re able to write our own custom validation middleware. For example, if you want to verify the various data inside req.body in a POST request you could write:

const customersCreateValidator = Celebrate({
body: Joi.object().keys({
email: Joi.string().email().required(),
first_name: Joi.string().required(),
last_name: Joi.string().required(),
notes: Joi.string(),
status: Joi.string().required(),
}),
});

In our customersCreateValidator we want to make sure we have a few specific required fields like email, first_name, and last_name, status, and optional fields like notes.

We could then use that middleware like so:

app.post('/customers', customersCreateValidator, createCustomer);

Celebrate comes with it’s own configurable suite of well-formatted validation errors that you can plug in with ease.

Happy coding!


hexient-labs

Tiny thoughts from the team at Hexient Labs

Mitch Masia

Written by

Mitch is a developer, teacher, and entrepreneur building cool things at Guaranteed Rate.

hexient-labs

Tiny thoughts from the team at Hexient Labs

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade