validatar
Javascript data validator.
A simple way to validate date and customerize the constraint.
Installation
npm install validatar
Links
npm package
Github page
async-validatar
Usage
Example
const Validatar = ; Validatar;Validatar; const data = str1: 'I am a string!' obj1: str2: 456 ; const rule = str1: constraint: 'isString' message: 'str1 must be string' obj1: str2: 'required' 'isString' ; const result = Validatar;console;// expected output:// {// constraintId: 'isString',// position: 'obj1.str2',// key: 'str2',// value: 456,// params: undefined,// message: 'str2 is not a string. value:456 position:obj1.str2',// }
Pass parameters to check function
const Validatar = ; Validatar;Validatar; const data = str1: 'I am a string!'; const rule = str1: 'isString' constraint: 'checkLength' params: 5 12 ; const result = Validatar;console;// expected output:// {// constraintId: 'checkLength',// position: 'str1',// key: 'str1',// value: 'I am a string!',// params: [5, 12],// message: 'str1 length error.',// }
Main Function
Validatar.register
/** * Register a constraint * @param * @param {Any truthy value} message: The message of the constraint. Will return when the constraint is violated. * @param */Validatar;
Validatar.validate
/** * Validate the input data * @param * @param * @return {undefined | Object} return undefined if pass the rule.return object if any constraint in the rule is violated. * { * constraintId: * position: * key: * value: * params: * message: * } */const result = Validatar;
Another Example
const Validatar = ; Validatar;Validatar;Validatar; const correctData = str1: 'I am a string!' obj1: email: 'random@email.com' ; const rule = str1: constraint: 'required' message: 'str1 not exists' constraint: 'isString' message: 'str1 must be string' obj1: email: 'required' 'isString' 'isEmail' ; const correctResult = Validatar;console;// expected output: undefined const wrongData = str1: 'I am a string!'; const wrongResult = Validatar;console;// expected output:// {// constraintId: 'required',// position: 'obj1.email',// key: 'email',// value: undefined,// params: undefined,// message: new Error('Wrong input format')// }