gladius-core
v0.1.0
Published
Atomic, modular value validation with easily configurable rules and defaults.
Downloads
168
Readme
gladius
Atomic, modular value validation with easily configurable rules and defaults. Zero dependencies.
Concepts
- Atomic validators — each rule (
isString,minLength,email, ...) does one thing and is created withcreateValidator(name, test, defaultOptions). - Configurable defaults — every validator exposes
.configure(options)to change its defaults globally, and accepts per-call options that override those defaults. - Composition — combine validators with
pipe(stop at first failure) orall(collect every failure). - Object schemas —
validateObjectmaps field names to composed validators.
Usage
import { required, isString, minLength, email, isNumber, min, pipe, validateObject } from 'gladius-core';
const validateUser = validateObject({
name: pipe(required(), isString(), minLength({ min: 2 })),
email: pipe(required(), email()),
age: pipe(required(), isNumber(), min({ min: 0 })),
});
validateUser({ name: 'Al', email: '[email protected]', age: 30 });
// => { valid: true, value: { ... } }
validateUser({ name: 'A', email: 'not-an-email', age: -1 });
// => { valid: false, value: { ... }, errors: { name: {...}, email: {...}, age: {...} } }Configuring defaults
minLength.configure({ message: (value, opts) => `Needs ${opts.min}+ characters` });Writing your own validator
import { createValidator } from 'gladius-core';
export const isEven = createValidator('isEven', (value) => value % 2 === 0, {
message: 'Value must be even',
});Test
npm test