Nutritious Pumpkin Meal

    input-validator

    0.2.3 • Public • Published

    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.

    Install

    npm i input-validator

    DownloadsWeekly Downloads

    16

    Version

    0.2.3

    License

    MIT

    Last publish

    Collaborators

    • emertechie
    • stephanbuys