Dead simple sync/async object validation library with focus on custom matchers.
Install
npm i entity-validator
How to use?
validate(params)
params.entity: Entity
params.matchers: Array,
params.attributes: Array,
You have entity for validate
const entity = {};
and attributes rules
const attributes = [
{
key: 'name',
rules: [ 'presence' ],
},
];
and matchers which used in rules
const presenceMatcher = {
key: 'presence',
check: (entity, attribute) => {
if (!attribute || !entity || entity[attribute]) return null;
return { messageKey: 'presenceText' };
},
};
const matchers = [ presenceMatcher ];
now you can get validation matchers errors!
const { validate } = require('entity-validator');
const { matchersErrors } = await validate({ entity, attributes, matchers });
Helpers
createAttributesByValidator(validator, params)
Tranform validator object (groupped attributes) to attributes.
const { createAttributesByValidator } = require('entity-valdiator');
const validator = {
key: 'user',
attributes: ({ passwordMinLength, passwordMaxLength }) => ([
{
key: 'email',
rules: [
'presence',
['length', { min: passwordMinLength, max: passwordMaxLength }],
]
},
])
};
const params = { passwordMinLength: 6, passwordMaxLength: 12 };
const attributes = createAttributesByValidator(validator, params);
Flow types
import type { Validator, } = from('entity-valdiator/build/types');