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

@touch4it/sails-hook-validator

v2.4.0

Published

Validation hook for Sails.js requests

Downloads

46

Readme

Sails.js request validation hook

Build Status Sails dependency version (scoped) Validator dependency version (scoped) GitHub license npm version node version vulnerabilities last commit

Sails hook for validate request.

  npm install --save @touch4it/sails-hook-validator

req.validator(rules, [sendResponse=true, [cb]])

Requirements:

  • Sails ^1.0.0
  • Lodash enabled as global in Sails (by default it comes enabled)
  • Node.js >= 10

rules

Rules defined as string parameter name (required string value) or object (more complex validation). Rules passed as array of strings or objects

Optional parameters prefixed with ?

Possible options specified later in "Validation types" section

req.validator(['name']);
req.validator([{'name': 'string'}]);
req.validator(['?name']);

sendResponse

true: If something goes wrong, return a 400 to the user with the error

false: Return

cb

Callback function

Return value

If something goes wrong it returns a 400 or false, based on sendResponse. If validation is successful, it returns the params. It works as a filter too, since it returns only parameters specified in rules.

Examples

Filter of parameters

If there is single parameter to be validated, we can pass it as string instead of array

  // req.params.all() === {name: 'joseba', surname: 'legarreta'}

  const params = req.validator('name');

  // params === {name: 'joseba'}

For more that one params the required params have to pass it as an Array

Missing parameter causes system to return 400 if second parameter (sendResponse) is not set or true. False is returned if second parameter is false

  // req.params.all() === {id: 1, name: 'joseba'}

  const params = req.validator(['id', 'password'], false);

  // params === false

  if (!params) {
    return null;
  }
  // req.params.all() === {id: 1, name: 'joseba'}

  const params = req.validator(['id', 'password']);

  // Sent 400 with message "password is required."

Callback function can be used to notify execution end

  const filter = [
    'id',
    '?name',
    {'?surname': ['string', 'toUpper']},
    height: 'float',
    '?age': 'int'
  ];
  req.validator(filter, false, function(err, params) {
    // err === {message: 'parsedError...', invalidParameters: ['invalid', 'parameter', 'list']}
    if (err) {
      return res.badRequest(err.message);
    }
    return res.ok(params);
  });

or

  const filter = [
    'id',
    '?name',
    {'?surname': ['string', 'toUpper']},
    height: 'float',
    '?age': 'int'
  ];
  req.validator(filter, function(err, params) {
    // If error occurs the validator will use req.status(400).send(...)
    return res.ok(params);
  });

Apart from validation, we can also use sanitization of inputs


  // req.params.all() === {id: 1, likes: '12.20', url: 'HttP://GOOGLE.eS', email: '[email protected]'}
  const params = req.validator(['id', {likes: 'int', url: ['url', 'toLower'], email: 'email'}]);
  // params = {id: 1, likes: 12, url: 'http://google.es', email: '[email protected]'}
  // req.params.all() === {id: 1, likes: '12.20', url: 'http://google.es', email: '[email protected]'}
  const params = req.validator(['id', 'url', {likes: 'float', email: 'email'}]);
  // params = {id: 1, likes: 12.20, url: 'http://google.es', email: '[email protected]'}
  // req.params.all() === {id: 1, likes: 'hello', url: 'http://google.es', email: '[email protected]'}
  const params = req.validator(['id', {url: ['url', 'lower'], likes: 'float', email: 'email'}]);
  // Client gets a 400 - 'likes' has to be a float

We can also specify optional values by prefixing ?

  // If we have a nickname and/or a name parameters it will return it to the `param`  applying the rules
  // If nickname or/and name are undefined in the request, it will ignore them and won't send 400

  const param = req.validator('?nickname', {color: ['hexcolor', 'upper'], '?name': 'toUpper'});

Validation

Validation uses validator package under the hood

Validation types

  • alpha - letters only
  • alphanumeric - letters and numbers
  • ascii
  • base64
  • boolean
  • country2 - ISO 3166-1 alpha-2
  • country3 - ISO 3166-1 alpha-3
  • creditCard
  • date - ISO 8601 or RFC 3339 date
  • email
  • empty
  • float
  • fqdn - fully qualified domain name
  • hex
  • hexColor
  • int
  • ip - IPv4 or IPv6
  • ipRange - IPv4 range
  • isbn - ISBN
  • issn - ISSN
  • isin - ISIN
  • isrc - ISRC
  • json
  • jwt
  • latlon
  • lower - lowercase
  • macAddress
  • mobilePhone
  • md5
  • mongoId
  • numeric
  • port
  • string
  • upper - uppercase
  • uuid - UUID v 3, 4 or 5
  • url

Sanitization types

  • escape - replace <, >, &, ', " and / with HTML entities
  • unescape - replaces HTML encoded entities with <, >, &, ', " and /
  • trim - trim whitespaces from left and right
  • ltrim - trim whitespaces from left
  • rtrim - trim whitespaces from right
  • toBoolean
  • toDate
  • toEmail
  • toLower
  • toUpper

Tests

To test this hook, you need mocha installed in your computer globally.

// Just if you don't have mocha installed yet
npm install -g mocha

// And then just run mocha in the hook folder

mocha

// Optional: Change port or log level

log=info port=1234 mocha

// log level options = error, warn, info, verbose and silly. By default: warn
// port by default: 1992