npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

input-validator

v0.2.3

Published

Validates and whitelists input data using Joi schemas and/or custom functions

Downloads

26

Readme

input-validator

Validates and whitelists input data using Joi schemas and/or custom functions.

Install

npm install input-validator

Overview

Example usage in a Node express app:

var express = require('express');
var app = express();
var Joi = require('joi');
var validate = require('input-validator');

var customerSchema = Joi.object().keys({
    name: Joi.string().min(5).max(50),
    // ... etc
});

app.post('/createCustomer', function(req, res) {
  var vInput = validate(req.params, customerSchema);
  
  // vInput now contains 'name' from req.params (assuming it validated ok), and nothing else
  // `validate` function will throw a `ValidationError` if anything amiss

  // ...
});

API

var validate = require('input-validator');

// FORM 1:
var whitelistedData = validate( data /* ,[data]*, [schema|validationFn]+ */ );

// E.g:
// var whitelistedData = validate(req.query, customerCodeSchema);
// var whitelistedData = validate(req.query, req.params, schemas.paging, schemas.sorting);

// or, FORM 2:
var whitelistedData = validate(
    [data1, schemaOrFunc /* [schema|validationFn]* */ ],
    [data2, schemaOrFunc /* [schema|validationFn]* */ ],
    // ...
);

// E.g:
// var whitelistedData = validate(
//    [req.query, schemas.paging, schemas.sorting],
//    [req.params, customerCodeSchema, myCustomFunc]
// );

The validate function takes:

  • One or more 'data' objects (such as req.params, req.query in a web app).
  • Multiple data objects are merged internally before validation is applied.
  • One or more Joi schemas or custom validator functions
  • The Joi schema should be of the type Joi.object().keys({ ... }). See the Joi repo for docs
  • See below for custom validation function

Custom Validation Function

As of the time of creating this repo, Joi does not currently support defining custom validators (although it's a WIP). To get around this and to allow full control, this library supports custom functions of the form:

function(mergedRawInputData, validDataSoFar) {
    var rawValue = mergedRawInputData.foo;
    return {
        valid: true|false,
        message: '"foo" must be 1 when "bar" is true',
        value: {
            foo: rawValue
        }
    };
}

Hopefully the param names give it away, but the mergedRawInputData is the raw, unvalidated input; validDataSoFar is all the validated (and hence whitelisted) data processed so far. I.e. if you have:

var validate = require('input-validator');
var whitelistedData = validate( data1, data2, schema1, myFunc, schema3 );

then myFunc will receive as the second param only data in data1 or data2 which is validated by schema1.

Common Schemas Pattern

A useful pattern can be to have a library of shared schema types. E.g:

// schemas.js

module.exports = {
    paging: Joi.object().keys({
        pageFrom: Joi.number().integer().min(0).max(10000).required(),
        pageSize: Joi.number().integer().min(1).max(50).required()
    }),
    customerCode: Joi.object().keys({
        custCode: Joi.string().regex(/whatever/).required()
    })
};
// app.js

var schemas = require('./schemas');

var express = require('express');
var app = express();
var Joi = require('joi');
var validate = require('input-validator');

var customerSchema = Joi.object().keys({
    name: Joi.string().min(5).max(50),
    // ... etc
});

app.get('/customer/:custCode', function(req, res) {
  var vInput = validate(req.query, req.params, schemas.paging, schemas.customerCode);
  
  // For the query: "GET /customer/foo?pageFrom=0&pageSize=10&thisIsIgnored=true", vInput will contain:
  // { pageFrom: 0, pageSize: 10, custCode: 'foo' }

  // As always, `validate` function will throw a `ValidationError` if anything does not validate ok
});

License

The MIT License (MIT)

Copyright (c) Panoptix CC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.