This is a bare minimum validation tool for js.
npm install @laranatech/schemer
See @laranatech/schemer on npm.
// Browser
import { rules, Schemer } from '@laranatech/schemer'
// Node.js
const { rules, Schemer } = require('@laranatech/schemer')
const { validate, rules } = require('@laranatech/schemer')
// returns `true` if value is valid
// throws an error otherwise
validate(20, {
type: 'int',
rules: [
rules.max(100),
rules.min(10),
],
})
validate([1, 2, 3], {
type: ['int'], // validating an array
rules: [
rules.positive(),
],
})
// type shorthands
validate(value, 'int')
validate([value], ['int'])
Value can be validated without throwing an error
const { success, errors } = validateSafely(10.1, 'int')
console.log(errors) // ['Error: Value must be integer: 10.1']
const { Schemer, rules, common } = require('@laranatech/schemer')
const s = new Schemer({
id: {
type: 'string',
rules: [
rules.regexp(/\d\d\d-\d\d\d/),
],
},
x: 'int',
y: common.positiveInt,
name: {
type: 'string',
nullable: true,
},
email: {
...common.email,
required: false,
},
})
s.validate({
x: undefined,
y: 10,
name: null,
email: '[email protected]',
})
// Error: value must be integer: undefined