Sandhands Docs

Exports

This section describes the usage of Sandhands's exports. To see the more about the sanitation format please see here.

Sanitize

Throws the first error found in the input.

const {sanitize} = require('sandhands')

sanitize(1, String) // throws error with message "Invalid Type"
sanitize(14, {_: Number, min: 22}) // throws error with message "Too small"

Valid

Returns a boolean repesenting whether or not the input matched the format.

const {valid} = require('sandhands')

console.log(valid(12, String)) // false
console.log(valid('', String)) // false (the default minimum string length is 1)
console.log(valid('foo bar', String)) // true

Details

Returns a array/object representing where and what the errors are dependant upon the format

const {details} = require('sandhands')

console.log(details(12, String)) // "Invalid Type"
console.log(details('', String)) // "Too short"
console.log(details('foo bar', String)) // null
console.log(details({a: 24}, {a: String, b: String})) // {a: "Expected String", b: "Property Required"}

Format

Shorthand for creating formats that have options. This can be useful for writing inline options.

import {details, Format, F} from 'sandhands'

console.log(details('Mixed Case', Format(String).lowercase())) // "Lowercase Only"
console.log(details('myname@jef.com', F(String).email().minLength(25))) // "Too short"
console.log(details({name: Format(String).lowerCase()})) // Also writeable as {_: String, lowercase: true}

Set Default

Set the default options for any data type

const {setDefault, valid} = require('sandhands')
console.log(valid('', String)) // returns false because the default minimum length for strings is 1
setDefault(String, {minLength: 0})
console.log(valid('', String)) // returns true because we've now lowered the minimum length to 0

Custom Format

Set a custom format. The default custom formats can be found here, but they can be overriden.

const {valid, customFormat} = require('sandhands')
customFormat('ticketNumber', {_: Number, min: 1000, max: 2000})
console.log(valid(12, 'ticketNumber')) // false
console.log(valid(1532, 'ticketNumber')) // true
consooe.log(valid(1523, {_: 'ticketNumber', even: true})) // false

Sandhands Express

The express middleware allows you to seamlessly sanitize your inputs. You must also use a body parsing library in conjunction to set the req.body to be sanitized.

const server = require('express')()
const {sandhandsExpress} = require('sandhands')
const bodyParser = require('body-parser')

server.use(bodyParser.json())

server.post('/register', sandhandsExpress({
  username: 'username',
  email: 'email',
  password: 'password'
}), (req, res) => {
  console.log('Got Registration Details', req.body)
  res.send('Registered')
})

server.listen(8050, err => {
  if (err) return console.log(err)
  console.log("Server Running.")
})