bailer
v0.0.4
Published
Small validation library. Inspired by leonardoborges/bouncer.
Downloads
7
Readme
bailer
A lightweight validation library. Inspired by leonardoborges's bouncer for Clojure.
Setup
npm install bailer
Usage
Built-in validators are:
bailer.validations.required
Validates when notnull
orundefined
bailer.validations.email
Check email format via a regexpbailer.validations.number
Validates whentypeof
returns"number"
bailer.validations.string
Validates whentypeof
returns"string"
bailer.validations.object
Validates whentypeof
returns"object"
. Arrays are objects.
You can create your own (see here).
var b = require('bailer'),
v = b.validations;
// Define a dummy object.
var person = {name: "John", age: 20,
corporation: '',
email: "[email protected]"};
// Check if it matches the schema.
b.validate(person, {
name: [v.required],
age: [v.required],
email: [v.email]
});
// Every validations passed.
// Result:
null
Errors
b.validate(person, {
name: [b.required],
corporation: [b.required],
firstname: [b.required]
});
// Uh-oh. The person object object doesn't have a truthy corporation
// (it is empty) or firstname (it is undefined).
// Result:
{corporation: ["corporation must be present"],
firstname: ["firstname must be present"]}
You can use a custom message.
b.validate(person, {
corporation: [b.required, "What! You don't work for a corporation?!"]
});
// which results in:
{corporation: ["What! You don't work for a corporation?!"]}
Custom validators
A custom validator is a function
with this signature:
function customValidator(obj, attributeName) {
// Do your stuff here
// ...
var correctResult = obj[attributeName].length > 3;
// If the provided value is valid, return null.
// Otherwise, return a description.
return correctResult ? null : "".concat(attributename, " should contains at least 3 elements");
}