Simple Data Validation In JavaScript – superstruct

Category: Javascript , Recommended | December 2, 2017
Author: ianstormtaylor
Views Total: 67
Official Page: Go to website
Last Update: December 2, 2017
License: MIT

Preview:

Simple Data Validation In JavaScript – superstruct

Description:

superstruct is a JavaScript library to validate any data at runtime with no 3rd JavaScript dependencies.

Basic usage:

Install & download:

# Yarn
$ yarn add superstruct

# NPM
$ npm install superstruct --save

Import the superstruct.

import { struct } from 'superstruct'

Define a struct to validate with.

const User = struct({
  id: 'number',
  name: 'string',
  email: 'string',
  age: 'number',
  departments: ['string'],
  is_admin: 'boolean?',
})

Define data to be validated.

const data = {
  id: 1,
  name: 'Jane Smith',
  email: '[email protected]',
  age: 42,
  departments: ['engineering', 'product'],
}

Validate the data. In this case, the data is valid, so it won’t throw.

try {
  User(data)
  console.log('Valid!')
} catch (e) {
  throw e
}

Leave a Reply