Learn how to performs input validation in express with example.

In the last tutorial, we looked at how to post data to various endpoint with POST HTTP verb or method.

This article will look at the multiple ways to validate the input sent to various endpoints with POST.

We will look at how we can validate without any package then we will take a look at how we can use various package for data validation. For our case, we will look at the joi npm validation package.

Input validation

Assume that we are posting some data to a specific endpoint, let us say ‘/user’ endpoint, and we want to perform some validation before we create and save the data to the server.

Many developers believe that you should not trust the data sent by the client, so, lest use performs some validation rules.

Let’s say the user is sending us his name. First, we want to ensure that the name maintains some maximum number and shouldn’t be empty.

// route handler

router.post('/user', (req, res, next) => {
// check if the sent name is blank
if (!req.body.name || req.body.name.length < 3) {
// send back a 400 bad request
res.status(400).send("Name is required ans should be atleast 3 letter")
return
}
res.json({
status: 'success',
data: req.body
})
});

From the code snippet above, we are validating the user’s input.

You can notice we have an if statement that will take in the name and check whether it is blank or at least a three-letter word.

If it doesn’t pass the test, we will send a status code of 400 to the user other we will send the data back to the user.

#programming #programming-tips #javascript #javascript-development #expressjs

How to Handle Routing with Express
1.15 GEEK