📘
NavDoc by Bash School
GithubContact
📘
NavDoc by Bash School
  • 🎓Introduction
  • 🐢Getting Started
  • ⚡Changelog
  • 👨‍🚀Maintainers
  • 🛣️Roadmap
  • Fundamentals
    • The Internet
      • Introduction
      • What is a URL
      • What is a port
      • The DNS protocol
      • The TCP protocol
      • The UDP protocol
      • The Web
      • The HTTP protocol
      • Hyperlinks
      • What is a Web browser
      • What is a Web server
    • HTML
      • Your first HTML page
      • Text tags
      • Attributes
      • Links
      • Images
      • Lists
      • Head Tags
      • Container tags
    • CSS
      • Introduction
      • Colors
      • selectors
      • Cascade
      • Specificity
      • Units
      • Advanced selectors
      • Typography
      • The box model
      • The display property
      • Responsive design
  • JavaScript
    • Basics
      • Introduction
      • Literals , Identifiers, Variables
      • Comments
      • The difference between let, const and var
      • Types
      • Operators and expressions
      • Arithmetic operators
      • The assignment operator
      • Operators precedence
      • Strings
      • Numbers
      • Semicolons, white space and sensitivity
      • Arrays
      • Conditionals
      • Loops
      • Functions
      • Objects
      • Arrays + functions
      • OOPS
      • Asynchronous
      • Scope, hoisting, event loop
      • ES Modules
      • Errors and exceptions
      • Built-in objects
        • The global object
        • Object properties
        • Number
        • String
        • Math
        • JSON
        • Date
        • Intl
        • Set and Map
      • More operators
    • Nodejs
      • Getting Started
      • Installation
      • Hello World in Node
      • Modules
      • Packages
      • File Handling
      • HTTP Request
      • Processing Files
      • HTTP
    • Express.js
      • Getting Started
      • Middleware
      • Serve Static Assets
      • How to Send Files to the Client
      • Sessions
      • Validate Input
      • Sanitizing Data
      • Forms
      • File Uploads
    • React
      • Setting up a React project with Vite
      • React Components
      • Introduction to JSX
      • Using JSX to compose UI
      • The difference between JSX and HTML
      • Embedding JavaScript in JSX
      • Handling user events
      • Managing state
      • Component props
      • Data flow
      • Lifecycle events
      • Managing forms in React
      • Install the React Developer Tools
      • Installing Tailwind CSS in a React app
      • Build a counter in React
    • TypeScript
      • Key Benefits
      • Types of Languages
      • The Need for TypeScript
      • What is TypeScript?
      • The tsc Compiler
      • Basic Types in TypeScript
      • tsconfig
      • Interfaces
      • Types
      • Arrays in TypeScript
      • Enums
      • Exporting and importing
    • MongoDB
      • SQL vs. NoSQL Databases
      • Installing MongoDB
      • MongoDB Databases and Collections
      • Working with Documents
      • MongoDB Operators
      • Sorting, Indexing & Searching
      • Built-in Methods
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. JavaScript
  2. Express.js

Validate Input

PreviousSessionsNextSanitizing Data

Last updated 1 year ago

Was this helpful?

Let's see how to validate any data coming in as input in your Express endpoints.

Say you have a POST endpoint that accepts the name, email, and age parameters:

const express = require('express')
const app = express()

app.use(express.json())

app.post('/form', (req, res) => {
  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

How do you perform server-side validation on those results to make sure that:

  • name is a string of at least 3 characters?

  • email is a real email?

  • age is a number, between 0 and 110?

The best way to handle validation on any kind of input coming from outside in Express is by using the :

npm install express-validator

You require the check and validationResult objects from the package:

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

We pass an array of check() calls as the second argument of the post() call. Every check() call accepts the parameter name as argument. Then we call validationResult() to verify there were no validation errors. If there are any, we tell them to the client:

app.post('/form', [
  check('name').isLength({ min: 3 }),
  check('email').isEmail(),
  check('age').isNumeric()
], (req, res) => {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() })
  }

  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

Notice I used:

  • isLength()

  • isEmail()

  • isNumeric()

  • contains(), checks if value contains the specified value

  • equals(), checks if value equals the specified value

  • isAlpha()

  • isAlphanumeric()

  • isAscii()

  • isBase64()

  • isBoolean()

  • isCurrency()

  • isDecimal()

  • isEmpty()

  • isFQDN(), checks if it's a fully qualified domain name

  • isFloat()

  • isHash()

  • isHexColor()

  • isIP()

  • isIn(), checks if the value is in an array of allowed values

  • isInt()

  • isJSON()

  • isLatLong()

  • isLength()

  • isLowercase()

  • isMobilePhone()

  • isNumeric()

  • isPostalCode()

  • isURL()

  • isUppercase()

  • isWhitelisted(), checks the input against a whitelist of allowed characters

You can validate the input against a regular expression using matches().

Dates can be checked using:

  • isAfter(), checks if the entered date is after the one you pass

  • isBefore(), checks if the entered date is before the one you pass

  • isISO8601()

  • isRFC3339()

All those checks can be combined by piping them:

check('name')
  .isAlpha()
  .isLength({ min: 10 })

If there is any error, the server automatically sends a response to communicate the error. For example if the email is not valid, this is what will be returned:

{
  "errors": [{
    "location": "body",
    "msg": "Invalid value",
    "param": "email"
  }]
}

This default error can be overridden for each check you perform, using withMessage():

check('name')
  .isAlpha()
  .withMessage('Must be only alphabetical chars')
  .isLength({ min: 10 })
  .withMessage('Must be at least 10 chars long')

What if you want to write your own special, custom validator? You can use the custom validator.

In the callback function you can reject the validation either by throwing an exception, or by returning a rejected promise:

app.post('/form', [
  check('name').isLength({ min: 3 }),
  check('email').custom(email => {
    if (alreadyHaveEmail(email)) {
      throw new Error('Email already registered')
    }
  }),
  check('age').isNumeric()
], (req, res) => {
  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

The custom validator:

check('email').custom(email => {
  if (alreadyHaveEmail(email)) {
    throw new Error('Email already registered')
  }
})

can be rewritten like this:

check('email').custom(email => {
  if (alreadyHaveEmail(email)) {
    return Promise.reject('Email already registered')
  }
})

There are many more of these methods, all coming from , including:

For exact details on how to use those validators, .

express-validator package
validator.js
refer to the docs here