0.1.0 • Published 9 years ago
map-validator v0.1.0
map-validator
An object validator based on node-validator. Heavily inspired by express-validator.
Installation
npm install map-validator --save
Usage
var MapValidator = require('map-validator');
// our key-value data object
var postBody = {
name: 'John Doe',
email: 'John.Doe@Example.com'
// more data here...
};
// create validator for our object
var validator = new MapValidator(postBody);
// validate object keys
validator.check('name', 'Name is required').notEmpty().isLength(5);
validator.check('email', 'Invalid email').isEmail();
validator.check('age', 'Invalid age').optional().isInt({min: 18, max: 99});
validator.sanitize('email').normalizeEmail();
validator.sanitize('age').toInt();
var errors = validator.verify();
if(errors)
throw errors;
console.log(postBody);
Which will result:
{ name: 'John Doe', email: 'john.doe@example.com' }
API
instance.verify
function(mappedErrors)
Return all the errors or null
.
The mappedErrors
option can be used to return the errors as key-value map or
as an array (default). On mappedErrors
mode, if two or more errors occur on the
same key, the first error will be chosen.
errors:
[
{key: "email", error: "required", value: "<received input>"},
{key: "email", error: "valid email required", value: "<received input>"},
{key: "password", error: "6 to 20 characters required", value: "<received input>"}
]
mappedErrors:
{
email: {
key: "email",
error: "required",
value: "<received input>"
},
password: {
key: "password",
error: "6 to 20 characters required",
value: "<received input>"
}
}
MapValidator.extend
function(name, fn)
Used to add your own validators:
MapValidator.extend('isWhitespace', function(str) {
return /^\s+$/.test(str);
});
MapValidator.sanitizerExtend
function(name, fn)
Used to add your own sanitizers:
MapValidator.sanitizerExtend('toLowerCase', function(str) {
return String(str).toLowerCase();
});
License
Copyright © 2015 Moshe Simantov ms@development.co.il, MIT License