variable-value-validator
v1.0.1
Published
Minimal schema validation for TypeScript and JavaScript.
Maintainers
Readme
What is it ?
variable-value-validator is a minimal (standard-schema compliant) schema validation library enabling type-safe code with unsafe data such as serialized data, API responses, and more.
Example
// defining a schema describing the user object :
const userSchema = vvv.object({
id: vvv.number(),
name: vvv.string(),
isActive: vvv.boolean({ optional: true }),
tags: vvv.array(vvv.string()),
})
// if a TypeScript type is needed it can be inferred from the schema :
type User = SchemaToType<typeof userSchema>
// example unsafe data :
const response = await fetch("api.com/user/1")
const user = await response.json()
if (userSchema.guard(user)) {
// `user` is now guaranteed to be of type User
}Installation
# npm
npm install variable-value-validator
# yarn
yarn add variable-value-validator
# pnpm
pnpm add variable-value-validatorSchema creation methods
- Primitives:
vvv.string(),vvv.number(),vvv.boolean(),vvv.undefined(),vvv.null(),vvv.nullish()(null or undefined),vvv.function()andvvv.unknown()(always valid). - Objects:
vvv.object(shape: Record<string, Schema>),vvv.array(items: Schema[]),record(values: Schema[]),set(values: Schema[]),map(keys: Schema[], values: Schema[]),vvv.instance(constructor: new (...args: any[]) => Object)(class instances). - Other:
vvv.union(members: Schema[])("OR" schema association).
All of the schema creation methods accept an optional options object which can have the following optional properties:
optional: Marks the property as optional when used withvvv.object(e.g.vvv.object({ foo: string({ optional: true }) })).predicates: A function or an array of functions to add custom validation (e.g.vvv.number({ predicates: (num) => Number.isInteger(num) })).
Schemas
Every schema has the following methods :
guard(value: unknown): A type guard for that schema. If thevalueis valid in respect to that schema it will returntrue, else it will returnfalse.errors(value: unknown): An array of issues, a validvaluereturns an empty array.
