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

infi-validator

v1.1.1

Published

A simple request validator for Express.js apps

Downloads

17

Readme

infi-validator

Build Status npm NPM David

This library is a specially targeted module for Express.js applications to validate and sanitize incoming requests with predefined helpers. It can be integrated with all kinds of frameworks and libraries. Specific functionality of this library can be used on simple or complex plain objects.

Install

$ npm install infi-validator

Usage

Include the library into your project, build a Express.js route handler and create an instance of the validator class.

const InfiValidator = require('infi-validator');

app.get('/login', function(req, res) {
    const validator = new InfiValidator(req);
    validator
        .checkValues('params', {
            id: 'isMongoId'
        });

    const hasError = validator.hasErrors();

    if (hasError) {
        const err = validator.getFirstError();
        return res.status(err.code).send({
            code: err.code,
            message: err.message
        });
    }

    // ...

});

Specify the path of the request object, list the properties included in the object and assign helpers to be run against the values of the specified properties. Available paths are as follows:

  • params
  • body
  • query

In order to check if the validator detected an invalid value, use the hasErrors() method. Based on the flag returned by this function, you can perform further operations like throwing an error or sending a response back to the client with automatically generated code and message from the template generator.

Method getFirstError() returns error details containing code and message that were collected at the time of encountering the first incorrect value. You can also use getErrors() method to get all errors that were thrown during the validation check.

Multiple validators on a single property

It is possible to run multiple validators against a single property by placing them into an array:

validator
    .checkValues('params', {
        id: ['isExists', 'isMongoId']
    });

Chainable validations

You can chain checkValues() together to validate several locations at once:

validator
    .checkValues('params', {
        id: ['isExists', 'isMongoId']
    })
    .checkValues('body', {
        name: ['isExists', 'isString'],
        age: ['isExists', 'isNumber'],
        languages: 'isNotEmpty'
    });

Sanitization

You can sanitize incoming requests by stripping off vulnerable keywords from properties and replacing their values to a sanitized form. The library examines values for XSS and No-SQL Injection occurrences.

In order to sanitize incoming request, use the cleanInjections() method:

/* 
{
    username: "admin",
    password: "<script>alert('xss');</script>",
    role: {
        $eq: {
            $ne: "not-not-admin"
        }
    }
}
*/

validator.cleanInjections();

const { body } = validator.getSafeObject();

console.log('is body safe?', body);
/* is body safe?
{
    username: "admin",
    password: "&lt;script&gt;alert('xss');&lt;/script&gt;",
    role: {
        eq: {
            ne: "not-not-admin"
        }
    }
}
*/

The sanitized body object is available on the getSafeObject() method call. As for the cleanInjections() method, it iterates over the data recursively and cleans off every encountered injection and vulnerability, thus you can continue to work on this object safely.

List of validators

Validators are divided into two groups: simple and complex. Simple validators are mainly used to check the type of passed value. Available validators are listed below:

isNotEmpty, isExists, isString, isNumber, isBoolean, isObject, isArray 
isFirebaseId, isUUIDv1, isUUIDv4, isMongoId

Complex validators are used to check specific condition based on a argument that was passed after the colon.

hasLength:n (type n => number)
hasArrayItem:v (type v => number | string | boolean | null | undefined)
hasObjectKey:k (type k => number | string)

Example of using a complex validator:

validator
    .checkValues('body', {
        items: ['isArray', 'hasLength:3', 'hasArrayItem:flowers']
    });

Tests

$ npm install
$ npm test

Contribution

I encourage everyone to contribute to this project by extending the functionality, adding new features and validators. Before creating a pull request, please refer to the pull request guideline.

Author

Piotr Sobuś

License

This project is licensed under the MIT license. See the LICENSE file for more info.