Server side Validation

Learning Objective

Pre-requisites

Lesson

Most websites have client-side validation in place. For example, a sign-up form may disable the submit button until all the fields have been filled in. However, client side validation can be subverted either by disabling JavaScript in the browser, or, by using a tool such as Postman to call the API directly, bypassing the form.

Listen to this short video (3mins) which explains why this can be a problem. Also think back to Unit 3 when we discussed SQL injection attacks.

In this lesson you are going to use Express validator to add some server side validation to ensure that a user cannot send in malicious input which could expose sensitive data or hack your application.

To install Express Validator run:

npm install express-validator

Require this in your server.js file

const { check, validationResult } = require('express-validator');

You can now add validation to your route, for example, to escape any HTML characters in the restaurant name field:

app.post('/restaurants', [
    check('name').not().isEmpty().trim().escape()
    ], async (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }

Assignment

  1. Use the express validator documentation to add server-side validation to your routes. Include validators for the following:

  2. Commit your code into Github and share the link with your coach for review

Assignment extension tasks

Add sensible server-side validation to all of your deleting and updating endpoints.