Proxy-validation
A very basic and simple validation utility that can be used as a helper when validating JS-objects. No smart built-in validators because - different business rules often requires custom/special validators.
You'll need to implement your own validate
methods!
Code examples
Simple example #1:
const ProxyValidation = ; const UserValidationFields = name: { // Just validate that the value is not "falsy" if !value throw `Cannot set to: `; } ; const user = ProxyValidation; user; // OKusername = ''; // Throws TypeError: Cannot set name to ''
Simple example #2 (using ES6 class):
const ProxyValidation = ;const StringValidator = ; const UserValidationFields = firstName: min: 3 max: 10 validate: StringValidatorvalidateField email: regexp: /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/ min: 5 max: 200 // Custom (naive) validation method. { StringValidator; if !fieldregexp throw `Expected to be a email address`; } ; super(UserValidationFields); return super.initializeValidation(); } const user = ;userfirstName = '1'; // Throws RangeError (string should be between 3 and 10 characters)userfirstName = 1; // Throws TypeError (not a string)useremail = 's@@@@error'; // Throws TypeError (expected email to be a email address)userunknown = ; // Throws Error (Unknown field)
Examples with validation options
const user1 = ProxyValidation;user1name = null; // OKuser1; // TypeError: Cannot set name to null const user2 = ProxyValidation;user2name = null; // TypeError: Cannot set name to null const user3 = ProxyValidation;user3unknownField = 'bar';user3; // OK const user4 = ProxyValidation;user4unknownField = 'bar';user4; // OK
For more examples, see /test.
Requirements
Node 6+
Developing
# install dependencies npm i# run tests npm test# lint npm run eslint# check coverage npm run coverage# install, lint, test & coverage npm run build-all