shapeit
Version:
Object validation tools for Javascript and, specially, Typescript
62 lines (61 loc) • 1.65 kB
TypeScript
import { NonEmptyArray } from '../types/utils';
import { RulesSet, ValidationResult } from '../types/validation';
/**
* Validates an object against one or multiple sets of rules.
*
* A set of rules can be
*
* 1. A validation function that receives the original object and the assert
* function
*
* 2. A validation object containing some of the input's keys, each one matching
* a set of rules for the corresponding key on the input
*
* 3. An array containing multiple sets of rules
*
* @example
* const number = 10;
*
* const result = await validate(number, async (number, assert) => {
* assert(number < 0, 'Number must be negative');
* await doSomethingWithAnAPI(number, assert);
* });
*
* @example
* const person = {
* name: 'John',
* age: 32
* };
*
* const result = await validate(person, {
* name: (name, assert) => {
* assert(name === 'John', 'You must be John');
* },
* age: (age, assert) => {
* assert(age >= 18, 'You must be at least 18 years old');
* }
* });
*
* @example
* const person = {
* name: 'John',
* age: 32,
* yearsOfExperience: 5
* };
*
* const result = await validate(person, [
* (person, assert) => assert(
* person.yearsOfExperience < person.age,
* 'You cannot have worked THAT hard'
* ),
* {
* name: (name, assert) => {
* assert(name === 'John', 'You must be John');
* },
* age: (age, assert) => {
* assert(age >= 18, 'You must be at least 18 years old');
* }
* }
* ]);
*/
export default function validate<T>(input: T, ...rules: NonEmptyArray<RulesSet<T>>): Promise<ValidationResult>;