Previous Lecture Complete and continue  

  Course Content

Joi.js Input Validation (Part 1)

Joi.js Input Validation (Part 1)

Table Of Contents


  1. Understand how to approach input validation (useful for any input validation library)
  2. Learn how to create json validation schemas within Joi.js

What is Joi?

Why Leverage Joi?

Types Of Input Validation (Question)

Types Of Input Validation (Answer)

Joi Advantages

Joi Advantages (CONT.)

Joi Schemas

Joi Schemas (CONT.)

Additional Joi Types

Ex: Joi Bypass (Question)

Ex: Joi Schema/Payload

const Joi = require('joi');

const schema = Joi.object()
    // Requires a given string value
    username: Joi.string()
    // Define password complexity requirements through regex (consider more complex regex)
    password: Joi.string()
    // Force passwords to match
    password_confirmation: Joi.any()
    // Accept different Joi types.  Optional, unconstrained string or number
    access_token: [Joi.string(), Joi.number()],
    // Required birthyear to be an int between range
    birthyear: Joi.number()
    // Validate email address from (remember spoofing considerations)
    email: Joi.string()
    marketing_opt_out: Joi.boolean(),
    csrf_token: Joi.string()
        version: 'uuidv4',
    sex: Joi.string()
      .equal(['M', 'F', 'MALE', 'FEMALE', 'DECLINE'])
    roles: Joi.object()
  // email must be accompanied by marketing_opt_out
  .with('email', 'marketing_opt_out');

const result = Joi.validate({
  username: 'Ronald',
  password: 'McDonald',
  password_confirmation: 'McDonald',
  birthyear: 2010,
  email: '',
  marketing_opt_out: true,
  csrf_token: '6d4d8c14-ef12-45d9-ab3c-5dddf941fb76',
  sex: 'F',
  time: 1534942475121,
  roles: {},
}, schema);

// If result.error === null, payload is valid
console.log(`The validation error is: ${result.error}`);

Ex: Joi Schema/Payload (Result)

The validation error is: null