@zcabjro/vivalidate v0.8.0
@zcabjo/vivalidate
Summary
Yet another JSON validation library? Yes!
- Type validation with a functional interface
- Build complex types from simple primitives
- Written in typescript
- Focuses on serializable JSON data types
Installation
npm install @zcabrjo/vivalidate
Usage
All validators implement a validate
method:
validate(value: unknown): Either<ValidationError[], T>;
Refer to @zcabjro/either-js for information about
Either
, but in short it provides a functional alternative to throwing exceptions. The returned value is either a collection of errors (validation can fail for more than one reason) or the validated type. You can distinguish between the two cases by usingisLeft
andisRight
, or you can use one of the other methods such asmap
orfold
.
Creating a validator
You can compose validator primitives to create more complex schemas. You can also use Infer
to infer the validated type of any validator. This saves us from having to declare our types twice.
import * as v from '@zcabjro/vivalidate';
const documentSchema = v.object({
id: v.string(),
objectType: v.literal('document'),
title: v.string(),
subtitle: v.string().optional(),
tags: v.array(v.string()),
version: v.number().integer().greaterThan(0),
published: v.string().map(s => new Date(s)),
});
type Document = v.Infer<typeof documentSchema>;
// {
// id: string;
// objectType: 'document',
// title: string;
// subtitle?: string | undefined;
// tags: string[];
// version: number;
// published: Date;
// }
Applying a validator
Once you have a validator, you just need to call the .validate(value: unknown)
method.
declare const json: unknown;
const doc = documentSchema.validate(json);
if (doc.isLeft) {
throw new Error(`validation failed with ${doc.get.length} errors`);
}
// Or instead of throwing
const title = doc.fold(() => 'default title', d => d.title);
Available validators
Type | Validates |
---|---|
any | - |
array | Arrays of supported types |
boolean | boolean (true or false ) |
literal | Literal string | number | boolean | null |
nullable | Allows null |
number | number |
object | Objects that satisfy a schema |
oneOf | Union from an array |
optional | Allows undefined |
string | string |
tuple | Tuples (fixed length arrays) of supported types |
union | Unions (OR) of supported types |
unknown | - |
Examples
Here are some examples of how to use validators. Successful examples will return the typed input inside Right
. Examples that fail will return Left<ValidationError[]>
.
any
// SUCCESS
v.any().validate(0);
v.any().validate('abc');
v.any().validate([1, 2, 'a', {}]);
array
// SUCCESS
v.array(v.number()).validate([]);
v.array(v.number()).validate([1, 2, 3]);
v.array(v.array(v.string())).validate([[], ['a', 'b']]);
// FAILURE
v.array(v.number()).validate([1, 2, 'a']);
v.array(v.array(v.string())).validate([[1], [2]]);
boolean
// SUCCESS
v.boolean().validate(true);
v.boolean().validate(false);
// FAILURE
v.boolean().validate(0);
v.boolean().validate('');
literal
// SUCCESS
v.literal(0).validate(0);
v.literal('abc').validate('abc');
v.literal(true).validate(true);
v.literal(null).validate(null);
// FAILURE
v.literal(0).validate(1);
v.literal('abc').validate('cba');
v.literal(true).validate(false);
v.literal(null).validate(undefined);
number
// SUCCESS
v.number().validate(0);
v.number().validate(0.05);
v.number().validate(-1);
v.number().validate(NaN);
v.number().validate(Infinity);
// FAILURE
v.number().validate('0');
v.number().validate(null);
object
// SUCCESS
v.object({ a: v.number() }).validate({ a: 0 });
v.object({ a: v.number() }).validate({ a: 0, b: '' });
// FAILURE
v.object({ a: v.number() }).validate({ b: 0 });
v.object({ a: v.number() }).validate({ b: '' });
string
// SUCCESS
v.string().validate('');
v.string().validate('Hello, World!');
// FAILURE
v.string().validate(null);
v.string().validate(['a', 'b']);
tuple
// SUCCESS
v.tuple(v.string(), v.number()).validate(['a', 0]);
v.tuple(v.string(), v.string()).validate(['a', 'b']);
// FAILURE
v.tuple(v.string(), v.number()).validate([0, 'a']);
v.tuple(v.string(), v.string()).validate(['a', 'b', 'c']);
union
// SUCCESS
v.union(v.string(), v.number()).validate(123);
v.union(v.string(), v.number()).validate('abc');
// FAILURE
v.union(v.string(), v.number()).validate([123, 'abc']);
unknown
// SUCCESS
v.unknown().validate(0);
v.unknown().validate('abc');
v.unknown().validate([1, 2, 'a', {}]);
optional
// SUCCESS
v.string().optional().validate('example');
v.string().optional().validate(undefined);
// FAILURE
v.string().optional().validate(0);
v.string().optional().validate(null);
nullable
// SUCCESS
v.string().nullable().validate('example');
v.string().nullable().validate(null);
// FAILURE
v.string().nullable().validate(0);
v.string().nullable().validate(undefined);
and
const a = v.object({ a: v.number() });
const b = v.object({ b: v.string() });
const c = a.and(b);
// SUCCESS
c.validate({ a: 10, b: '' });
// FAILURE
c.validate({ a: 10 });
c.validate({ b: '' });
oneOf
enum MyEnum { A = 'A', B = 'B' };
// SUCCESS
v.oneOf(Object.values(MyEnum)).validate('A');
v.oneOf(Object.values(MyEnum)).validate('B');
// FAILURE
v.oneOf(Object.values(MyEnum)).validate('C');
Constraints
Constraints let you apply additional checks that aren't captured by the type-system.
Built-in constraints
// SUCCESS
v.array().length(1).validate(['a']);
v.array().lengthGreaterThan(2).validate(['a', 'b', 'c']);
v.array().lengthLessThan(3).validate(['a', 'b']);
v.number().integer().validate(0);
v.number().greaterThan(0.5).validate(1);
v.number().integer().lessThanOrEqualTo(10).validate(10);
v.object({ a: v.number() }).exact().validate({ a: 0 });
v.string().length(1).validate('a');
v.string().lengthGreaterThan(2).validate('abc');
v.string().lengthLessThan(3).validate('ab');
v.string().email().validate('first.last@example.com');
// FAILURE
v.array().length(1).validate([]);
v.array().lengthGreaterThan(2).validate(['a', 'b']);
v.array().lengthLessThan(3).validate(['a', 'b', 'c']);
v.number().integer().validate(0.5);
v.number().integer().greaterThan(0.5).validate(0.4);
v.number().lessThanOrEqualTo(10).validate(100);
v.object({ a: v.number() }).exact().validate({ a: 0, b: 1 });
v.string().length(1).validate('');
v.string().lengthGreaterThan(2).validate('ab');
v.string().lengthLessThan(3).validate('abc');
v.string().email().validate('invalid email');
Custom constraints
All validators implement a .constrain
method that lets you supply your own checks. Constraints are functions of type (value: T) => Either<ValidationError[], T>
.
v.string().constrain(s => s.startsWith("prefix"));
v.number().constrain(n => n % 2 === 0);
Transforms
Validation libraries often expose methods for transforming values as part of the validation process, reducing the amount of code the consumer has to write for what would otherwise have to be a two-stage process. Because vivalidate is backed by the Either
type, transformation is trivial to support using map
and flatMap
.
map
Using map
, we can validate an unknown value and then transform it from the validated type A
to a new type B
by passing an appropriate function. As a simple example, suppose we are validating an article like this:
const tags = v.array(v.string());
const article = v.object({ tags });
// {
// tags: string[];
// }
But we only care about the number of tags:
const tags = v.array(v.string());
const count = tags.map(ts => ts.length);
const article = v.object({ tags: count });
// {
// tags: number;
// }
OK that's pretty simple, but remember that we can do whatever we want inside the function:
const tags = v.array(v.string());
const count = tags.map(ts => {
// Count only special tags
const special = ts.filter(t => t.includes('special'));
return special.length;
});
const article = v.object({ tags: count });
// {
// tags: number;
// }
flatMap
We step things up a notch with flatMap
which is more powerful than map
in that the function you pass it is expected to return an Either
. Why is this powerful? Because it lets you apply transformations that can fail.
Suppose we have this schema:
const date = v.string();
const article = v.object({ date });
// {
// date: string;
// }
And suppose we'd rather date
be of type Date
after validation. You could do this manually after validation by parsing the validated string value. You could also attempt to use map
:
const date = v.string().map(s => new Date(s));
const article = v.object({ date });
// {
// date: Date;
// }
But if you want confidence that the date is valid, then you can use flatMap
:
import { Either, right } from '@zcabjro/either';
function toDate(s: string): v.Validated<Date> {
const date = new Date(s);
return isNaN(date.getTime()) ? v.invalid('invalid date') : right(date);
}
const date = v.string().flatMap(toDate);
const article = v.object({ date });
// {
// date: Date;
// }
Custom Errors
Many validators and constraints accept an optional error parameter, allowing you to override the error that gets raised when the validation or constraint fails.
const schema = v.object({
title: v.string().lengthGreaterThan(0, 'Title is required'),
ok: v.boolean('Ok must be true or false'),
author: v.literal('Anonymous', 'Author must be anonymous'),
});