v6e
Isomorphic functional validation
Install
$ npm install v6e
Example
const validator logic: all cond util: flatten rules: required length withIn format = ; const hobbySchema = name: ; // Let's define a custom rule!// This rule will not validate a single field directly but instead look for the attributes "width" and "height"// On the other fields (second parameter passed to the rule validator)const resolution = { return width < minWidth || height < minHeight ? error : null;}; // Because of the functional way rules are configured, you can make "templates" by using wrapping functionsconst highRes = ; // Lets define a CONDITION (note conditions are different from rules)// that checks on the photo if the "subject" equals "cat"const condCat = subject === 'cat'; const photoSchema = fileName: subject: width: height: resolution: ; const passwordConstraint = ; const minPhotos = ; const userSchema = username: password: passwordConstraint hobbies: hobbySchema photos: ; const validate = ; const input = username: 'sgtlambda' password: 'hunter2' dropTable: true hobbies: name: 'nitpicking' photos: fileName: 'funny.jpg' subject: 'cat' width: 400 height: 300 fileName: 'dangerous.pdf' subject: 'dog' width: 400 height: 300 ; ; // { // 'dropTable': 'Illegal attribute.',// 'password': 'Must be at least 8 characters long',// 'photos.0.resolution': 'Cat photos must be hi-res.',// 'photos.1.fileName': 'Please upload a jpg or png.' // }
Why?
- "Custom validators" that have to be registered on some singleton are awkward.
- Schemas should be declarative, readable and embeddable.
- Asynchronous rules should be supported by default and fully intermixable with synchronous rules.
- The purely functional nature encourages use of higher-order validators rather than some vaguely defined convention.
- Higher-order validators allow you to write infinitely complex validation logic using declarative and readable abstractions.
Why no field names in the validation errors?
- The errors object is a collection of
field: error
mappings, this is actually more useful for APIs. - The absence of field names within the messages themselves encourages UI design such that the error messages are placed above or underneath the actual field, as it should be anyways.
License
MIT © sgtlambda