Validating input in Express using express-validator
In this blog post, we will learn how to validate input data in your Express endpoints using the express-validator package. Specifically, we will look at how to validate the name, email, and age parameters in a POST endpoint.
Let’s start by setting up our Express server and configuring it to parse incoming JSON data:
1 | const express = require('express'); |
Next, let’s define our POST endpoint and perform validation on the input data:
1 | app.post('/form', [ |
In the above example, we are using the check() function from the express-validator package to validate each parameter. We are checking if the name is a string of at least 3 characters, if the email is a valid email address, and if the age is a number.
If any validation errors occur, we use the validationResult() function to get the errors and send them back to the client with a 422 status code.
The express-validator package provides a wide range of validation methods, all coming from validator.js. Some examples include isAlpha(), isNumeric(), isEmail(), isURL(), and many more.
You can also combine multiple validation checks by chaining them together:
1 | check('name') |
In addition to the built-in validation methods, you can also create custom validators using the custom() method. Here’s an example of how to use a custom validator to check if an email is already registered:
1 | check('email').custom(email => { |
Note that you can reject the validation by either throwing an exception or returning a rejected promise.
By leveraging the express-validator package, you can easily validate input data in your Express endpoints, ensuring that it meets your specific requirements. This improves the overall reliability and security of your application.
tags: [“Express”, “express-validator”, “validation”, “input data”, “server-side validation”]