Guardian
Data guard and validation library.
Validate user input with Guardian.
Install
npm i @olton/guardian
Using
import {parse, string, required, email, object} from "@olton/guardian"
const schema = string()
let value = parse(schema, "123")
console.log(value); // -> 123
let value = parse(schema, 123) // -> throw error
let value = safeParse(schema, 123) // -> return obj with error
if (!value.ok) {
console.log(value.error)
}
let value = safeParse(schema, "123") // -> return obj with data
if (value.ok) {
console.log(value.output)
}
let schema = object({
name: pipe(required("Name Required"), string()),
email: pipe(string(), email("Please enter a valid email address"))
})
const res0 = parse(schema, {
name: "Vasya Pupkin",
email: "vasya@pupkin.com"
}) // -> Ok
const res1 = parse(schema, {
name: "",
email: "vasya@pupkin.com"
}) // -> Error "Name Required"
const res2 = parse(schema, {
name: "Serhii Pimenov",
email: "vasya_pupkin.com"
}) // -> Error "Please enter a valid email address"
Parsing
Pipes
import {pipe, string, email} from "@olton/guardian"
const scheme1 = pipe(string(), email()) // left to right
const scheme2 = compose(email(), string()) // right to left
Create a simple schema
import {parse, object, visa, mastercard, string, email} from "@olton/guardian"
const schema1 = string()
const data1 = parse(schema1, "123")
const schema2 = pipe(required(), email())
const data2 = parse(schema2, "vasya@pupkin.com")
Create complex schema
import {parse, object, visa, mastercard, string, email} from "@olton/guardian"
const schema = object({
name: string(),
email: email(),
cards: object({
visa: visa(),
mastercard: mastercard()
})
})
const data = parse(schema, {...})
Guardians