Simple Data Validation In JavaScript – superstruct

Category: Javascript , Recommended | October 19, 2018
Author:ianstormtaylor
Views Total:242 views
Official Page:Go to website
Last Update:October 19, 2018
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
}

Changelog:

10/18/2018

  • v0.6.0

You Might Be Interested In:


Leave a Reply