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

koa-middle-validator

v1.2.0

Published

Koa middleware for the validator module. Support v1 and v2.

Downloads

405

Readme

koa-middle-validator

npm version

Koa middleware for the validator module. Support v1 and v2.

Installation

npm install koa-middle-validator

Usage

const util = require('util'),
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const convert = require('koa-convert');
const koaValidator = require('koa-middle-validator');
const Router = require('koa-router');
const _ = require('lodash');

const app = new Koa();
const router = new Router();

app.use(convert(bodyParser()));
app.use(koaValidator({
  customValidators: {
    isArray: function(value) {
      return _.isArray(value);
    },
    isAsyncTest: function(testparam) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          if (testparam === '42') { return resolve(); }
          reject();
        }, 200);
      });
    }
  },
  customSanitizers: {
    toTestSanitize: function() {
      return "!!!!";
    }
  }
})); // this line must be immediately after any of the bodyParser middlewares!

router.get(/\/test(\d+)/, validation);
router.get('/:testparam?', validation);
router.post('/:testparam?', validation);
app.use(router.routes())
app.use(router.allowedMethods({
  throw: true
}))

function validation (ctx) {
  ctx.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
  //ctx.checkParams('urlparam', 'Invalid urlparam').isAlpha();
  ctx.checkQuery('getparam', 'Invalid getparam').isInt();


  ctx.sanitizeBody('postparam').toBoolean();
  //ctx.sanitizeParams('urlparam').toBoolean();
  ctx.sanitizeQuery('getparam').toBoolean();

  ctx.sanitize('postparam').toBoolean();

  return ctx.getValidationResult().then(function(result) {
    ctx.body = {
      //
    }
  });
}

app.listen(8888);

Middleware Options

errorFormatter

function(param,msg,value)

customValidators

{ "validatorName": function(value, [additional arguments]), ... }

customSanitizers

{ "sanitizerName": function(value, [additional arguments]), ... }

Validation

ctx.check();

   ctx.check('testparam', 'Error Message').notEmpty().isInt();
   ctx.check('testparam.child', 'Error Message').isInt(); // find nested params
   ctx.check(['testparam', 'child'], 'Error Message').isInt(); // find nested params

ctx.assert();

Alias for ctx.check().

ctx.validate();

Alias for ctx.check().

ctx.checkBody();

Same as ctx.check(), but only looks in ctx.body.

ctx.checkQuery();

Same as ctx.check(), but only looks in ctx.query.

ctx.checkParams();

Same as ctx.check(), but only looks in ctx.params.

ctx.checkHeaders();

Only checks ctx.headers. This method is not covered by the general ctx.check().

~~ctx.checkCookies();~~

~~Only checks ctx.cookies. This method is not covered by the general ctx.check().~~

Validation by Schema

ctx.checkBody({
 'email': {
    optional: {
      options: { checkFalsy: true } // or: [{ checkFalsy: true }]
    },
    isEmail: {
      errorMessage: 'Invalid Email'
    }
  },
  'password': {
    notEmpty: true,
    matches: {
      options: ['example', 'i'] // pass options to the validator with the options property as an array
      // options: [/example/i] // matches also accepts the full expression in the first parameter
    },
    errorMessage: 'Invalid Password' // Error message for the parameter
  },
  'name.first': { //
    optional: true, // won't validate if field is empty
    isLength: {
      options: [{ min: 2, max: 10 }],
      errorMessage: 'Must be between 2 and 10 chars long' // Error message for the validator, takes precedent over parameter message
    },
    errorMessage: 'Invalid First Name'
  }
});

You can also define a specific location to validate against in the schema by adding in parameter as shown below:

ctx.check({
 'email': {
    in: 'query',
    notEmpty: true,
    isEmail: {
      errorMessage: 'Invalid Email'
    }
  }
});

ctx.check(schema); // will check 'password' no matter where it is but 'email' in query params

ctx.checkQuery(schema); // will check 'password' and 'email' in query params

ctx.checkBody(schema); // will check 'password' in body but 'email' in query params

ctx.checkParams(schema);

ctx.checkHeaders(schema); // will check 'password' in headers but 'email' in query params

Validation result

getValidationResult

Runs all validations and returns a validation result object for the errors gathered, for both sync and async validators.

ctx.assert('email', 'required').notEmpty();
ctx.assert('email', 'valid email required').isEmail();
ctx.assert('password', '6 to 20 characters required').len(6, 20);

ctx.getValidationResult().then(function(result) {
  // do something with the validation result
  if (!errors.isEmpty()) {
    ctx.body = errors.array();
  } else {
    // ctx.body = {};
  }
});

getValidationLegalResult (v1.1.0)

Runs all validations and return the validated values;

  try {
    ctx.checkBody({})

    const values = await ctx.getValidationLegalResult()

    mongoose.model.save(values)
  } catch (e) {
    // $$emit error
  }

Optional input

ctx.checkBody('email').optional().isEmail();
//if there is no error, ctx.request.body.email is either undefined or a valid mail.

Sanitizer

ctx.sanitize();


ctx.request.body.comment = 'a <span>comment</span>';
ctx.request.body.username = '   a user    ';

ctx.sanitize('comment').escape(); // returns 'a &lt;span&gt;comment&lt;/span&gt;'
ctx.sanitize('username').trim(); // returns 'a user'

console.log(ctx.request.body.comment); // 'a &lt;span&gt;comment&lt;/span&gt;'
console.log(ctx.request.body.username); // 'a user'

ctx.filter();

Alias for ctx.sanitize().

ctx.sanitizeBody();

Same as ctx.sanitize(), but only looks in ctx.request.body.

ctx.sanitizeQuery();

Same as ctx.sanitize(), but only looks in ctx.request.query.

ctx.sanitizeParams();

Same as ctx.sanitize(), but only looks in ctx.params.

ctx.sanitizeHeaders();

Only sanitizes ctx.headers. This method is not covered by the general ctx.sanitize().

~~ctx.sanitizeCookies();~~

~~Only sanitizes ctx.cookies. This method is not covered by the general ctx.sanitize().~~

Sanitizer result

getSanitizerLegalResult (v1.1.0)

Runs all sanitizer and return the sanitized values;

  try {
    ctx.sanitizeQuery('page').toInt()

    const values = await ctx.getSanitizerLegalResult()

    mongoose.model.save(values)
  } catch (e) {
    // $$emit error
  }