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

sails-hook-req-validate-promise

v1.7.1

Published

Validations in Sailsjs requests

Downloads

74

Readme

[DEPRECATION NOTICE]

sails-hook-req-validate-promise

Please use sails-hook-req-validate for the updated version! There is a brand new version that supports both PROMISE and Non-PROMISE versions with many new features.

I will no longer support this package but I will continue to update the sails-hook-req-validate package.



Sails hook for overwrite req.validate request with Promise.

Non-Promise version: https://www.npmjs.com/package/sails-hook-req-validate

  npm install sails-hook-req-validate-promise --save 

req.validate();

Requirements:

Sails v1.x.x and lodash enabled as global (lodash is enabled by default).


Default Value (when a parameter is not set)

  const params = await req.validate(['fruit', ['string', {default: 'apple'}]); // if 'fruit' doesn't exists, it will be set as 'apple'
  console.log(params);
  const params = await req.validate([
    {'fruit', {enum: ['apple', 'organe', 'bannana'], default: 'apple'}},   // also can be used with enum
    {'username?', 'string' }
  ]);
  console.log(params);

Enumeration check

  const params = await req.validate('fruit', {enum: ['apple', 'organe', 'bannana']});
  console.log(params);
  const params = await req.validate([
    {'fruit', {enum: ['apple', 'organe', 'bannana']}},
    {'username?', 'string' },
    {'nickname?', 'any' }   // any type
  ]);
  console.log(params);
  const params = await req.validate([
    {'fruit', ['string', {enum: ['apple', 'organe', 'bannana']}]},
    {'username?', 'string' }
  ]);
  console.log(params);

Simple Single & Multple Parameter(s)

Validates req.params for expecting parameter keys and returns req.badRequest (400 status code) if any parameter key is missing.

  try {
    const params = await req.validate('id');
    console.log(params);   // {id: '1234'} 
    // if the validation fails, "req.badRequest" will be called and returns Promise.reject
  } catch (err) {
    // wil catch Promise.reject here.
  }

If you prefer non async-await promise method

  req.validate('id');
    .then(params => {  
      console.log(params);   // {id: '1234'} 
    })
    .catch(err => {
      console.error(err);
    });

Disable req.badRequest on error and enable Promise.reject

  const params = await req.validate('id', false);  // <--- if you set the second value as FALSE, req.badRequest will NOT be call when error but it will just return Promise.reject

NOTE: To disable the default error response, set false as the second passing variable.

  const params = await req.validate(['id', 'firstname', 'lastname']);
  console.log(params);   // {id: '1234', firstname: "John", lastname: "Doe"}
  // if the validation fails, "req.badRequest" will be called and returns Promise.reject

Optional Parameter

Validates req.params for expecting parameter keys and returns req.badRequest (400 status code) if any parameter key is missing except optional parameters.

  const params = await req.validate(['id', 'firstname', 'lastname?']);  // lastname is an OPTIONAL field 
  console.log(params);   // {id: '1234', firstname: "John", lastname: "Doe"}
  // if the validation fails, "req.badRequest" will be called and returns Promise.reject

NOTE: For an optional parameter, just add ? at the end of the passing parameter key.

Multple Parameters with TYPE filters

Validates req.params for expecting parameter keys and returns req.badRequest (400 status code) if any missing parameter key.

  const params = await req.validate([
    {'id' : 'numeric'},
    {'firstname' : 'string'}, 
    {'lastname' : 'string'}
		]);
  console.log(params);   // {id: '1234', firstname: "John", lastname: "Doe"}

See Validation Filters for more information.

OR Operation

OR | operarion is a new addition to 0.2.x version. It can be applied to either required or optional parameter.

  const params = await rreq.validate(
      {'id': 'string | numeric'},   // 'numeric | string', 'numeric|string' or 'numeric| string' are OK. Space will be ignored
      {'usernameOrEmail': 'string | numeric | email'}
    );```
<br>


### Multple Parameters with TYPE filters & CONVERTION filters
Validates `req.params` for expecting parameter keys and returns `req.badRequest` (400 status code) if any missing parameter key.

```javascript
  const params = await rreq.validate([
		{'id' : 'numeric'},
		{'firstname' : ['string', 'toUppercase']}, 
		{'lastname' : ['string', 'toLowercase']}
		]);
  console.log(params);   // {id: '1234', firstname: "John", lastname: "Doe"}

NOTE: All CONVERTION filters start with to, for example: toUppercase, toBoolean.

See Validation Filters and Conversion Filters for more information.

- Additional Example (Combining All Above Examples in One)

Validates req.params for expecting parameter keys and returns req.badRequest (400 status code) if any missing parameter key.

  const params = await req.validate([
		{'id' : 'numeric'},                             // (required) 'id' param as NUMERIC type
		'phone?',                                       // (optional) 'phone' as ANY type
		{'website?': 'url'},                            // (optional) 'website' as URL type
		{'firstname' : ['string', 'toUppercase']},      // (required) 'firstname' as STRING type and convert to UPPERCASE
		{'department' : ['string', 'lowercase']}        // (required) 'department' as STRING type and must be LOWERCASE input
		]);
  console.log(params);   // {id: '1234', firstname: "John", lastname: "Doe"}
  // if the validation fails, "req.badRequest" will be called and will NOT returns Promise.reject

See Validation Filters and Conversion Filters for more information.

Disable Default Error Response

When the validation fails, res.badRequest will not be sent instead 'false' will be returned.

  try {
    const params = await req.validate(
      ['id', 'firstname', 'lastname?'],   // lastname is an OPTIONAL field 
      false  // <--- if you set the second value as FALSE, req.badRequest will NOT be call "res.badRequest" response when error but it will return Promise.reject                         
    );
    console.log(params);   // {id: '1234', firstname: "John", lastname: "Doe"}
    // ..process
  } catch (err) {
    console.error(err);
    return res.badRequest();    // Make sure to handle badRequest response
  }

NOTE: To disable the default error response, set false as the second passing variable.

Validation Filters

  any
  email
  url
  ip
  alpha
  numeric
  base64
  hex
  hexColor
  lowercase
  uppercase
  string
  boolean
  int
  float
  date
  json
  array
  object
  ascii
  mongoId
  alphanumeric
  creditCard

Conversion Filters

  toLowercase
  toUppercase
  toEmail         // Normalize email string 
  toBoolean
  toDate
  toInt
  toFloat