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

validator-utility

v1.1.1

Published

Extend validator functionality

Downloads

452

Readme

Validator Utility

CI

This package expands upon the functionality of the escape method in the validator package. It adds support for escaping string values in a JSON object, i.e., it'll escape all string values.

IMPORTANT: only use for responses, i.e., this function may be destructive:

  • If a key is named _id and its value is an object it'll try to do a .toString() on that value
  • If a value is an instanceof Date it'll call .toISOString() on that date value.

Install

Install/Update package (use latest release) with:

npm i validator-utility

Or download the standalone file (node10.4+)

Usage

const validator = require('validator-utility');
// NOTE: if the following depths are exceeded:
//  (1) objects will be truncated, and 
//  (2) arrays will not be processed (i.e., an empty array will be returned -- unless `truncateArray` is set to true).
validator.config({
  maxDeepDepth: 100,        // max deep depth (can be Infinity - default)
  maxArrayDepth: 100,       // max array depth (can be Infinity - default)
  suppressWarnings: false,  // supress warrning about truncated object or unprocessed arrays (false - default)
  ignore: [ '/' ],          // values to NOT escape (can be an empty array - default)
  truncateArray: false,     // if true process array but if maxArrayDepth is exceeded truncate (if set to false the array WILL NOT be processed - default)
});

// ...

app.post('/ping', (req, res) => {
  const example = {
    message: 'pong!',
    input: req.body.comment, // input: 'HELLO/WORLD <sneak>'
  };
  // ...
  const sanitizedResponse = validator.escape(example);
  return res.send(sanitizedResponse); // { message: 'pong!', input: 'HELLO/WORLD &lt;sneak&gt;'}
});

Example I/O

const input = '{ "message": "<sneak>" }'; // json string
// const output = validator.escape(input);
const output = '{ "message": "&lt;sneak&gt;" }'; // will return json string with appropriate values sanitized
const input = { message: '<sneak>' }; // object
// const output = validator.escape(input);
const output = { message: '&lt;sneak&gt;' }; // will return object with appropriate values sanitized
const input = [ { message: '<sneak>' }, ... ]; // arrays
// const output = validator.escape(input);
const output = [ { message: '&lt;sneak&gt;' }, ... ]; // will return array with appropriate values sanitized
const input = { _id: [Object] }; // objects with _id
// const output = validator.escape(input);
const output = { _id: 'id-...' }; // will call .toString() on the value of _id
const input = { date: new Date() }; // date
// const output = validator.escape(input);
const output = { date: '2021-12-04T10:35:06.353Z' }; // will return the date as an ISO string
const input = (a, b) => a + b; // function
// const output = validator.escape(input);
const output = (a, b) => a + b; // will return the function (same applies for things that are not objects or strings)

Types

declare module 'validator-utility' {
  /**
   * Replace `<`, `>`, `&`, `'`, `"` and `/` in every value inside an object
   * @param {any} obj the object/string to sanitize. Required.
   * @param {number} maxDeepDepth maximum allowed recursion depth.
   *                              `Infinity` by default.
   * @param {number} maxArrayDepth maximing allowed array size (depth).
   *                               `Infinity` by default.
   * @param {boolean} suppressWarnings wether to `console.warn` when an
   *                                  array/object exceeded the max depth.
   *                                  `false` by default.
   * @param {boolean} truncateArray if true, the array will be truncated if `maxArrayDepth` is
   *                                exceeded. If false, the array will not be processed if
   *                                `maxArrayDepth` is exceeded.
   *
   * @param {string[]|string} ignore characters that will NOT be escaped.
   * @returns the sanitized object/string. If the input is not a string or an object
   *          it'll be returned. If a JSON-String is inputed it'll parse it and return it back
   *          as a JSON-String (with the appropriate values sanitized).
   */
  export function escape<T>(
    obj: T,
    maxDeepDepth?: number,
    maxArrayDepth?: number,
    supressWarnings?: boolean,
    ignore?: string[] | string,
    truncateArray?: boolean,
  ): T;

  export type ValidatoUtilityOptions = {
    maxDeepDepth?: number,
    maxArrayDepth?: number,
    supressWarnings?: boolean,
    ignore?: string[] | string,
    truncateArray?: boolean,
  };

  export function config(options: ValidatoUtilityOptions): void;

  /**
   * Configures the member vairables:
   * @param {number} maxDeepDepth maximum allowed recursion depth.
   *                                        `Infinity` by default.
   * @param {number} maxArrayDepth maximing allowed array size (depth).
   *                                         `Infinity` by default.
   * @param {boolean} supressWarnings wether to `console.warn` when an
   *                                            array/object exceeded the max depth.
   *                                            `false` by default.
   * @param {string[]|string} blacklist a list of characters to NOT escape.
   */
  export function configure(
    maxDeepDepth?: number,
    maxArrayDepth?: number,
    supressWarnings?: boolean,
    ignore?: string[] | string,
    truncateArray?: boolean,
  ): void;
}

For documentation on other validator methods refer to the validator's documentation.