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

declare-validator

v1.1.0

Published

A thin wrapper around express-validator that allows for declarative config syntax

Downloads

5

Readme

declare-validator

A thin wrapper around express-validator that allows for declarative config syntax

Usage

Create an express app and hand it to the param validator init method, with an optional hash of options. These are generally just whatever options you want to pass to express-validator, which this package will set up for you.

// app.js

var express = require('express')
  , validator = require('declare-validator')
  , app = express()
  ;

validator.init(app, options);

There are three default values declare-validator will use if you don't pass them in the options hash.

  1. bodyParser - if you don't want declare-validator to do the body-parser setup, you can set it up yourself (otherwise it will default to bodyParser.json()). Note: You should pass the output of the run function, like bodyParser.json(), not the function itself.
  2. errorFormatter - the express-validator error formatter you want to use for validation error formatting, this package includes a default.
  3. customValidators - this is also a hash of functions to be used as validation methods, alongside the regular node-validator validation methods. There are also a core set of custom validations that are set by this package--your custom hash here will be merged into that object before being passed to express-validator. Passed in validation methods will override the core ones we include in this package, if the key names match.

Creating the Middleware

Create a validation middleware that uses any of the validators from the node-validator library or any of the custom validators found in lib/custom.js, or that you passed in during init.

// lib/validators/CreateAccountValidator.js

var util = require('util')
  , Middleware = require('declare-validator').Middleware
  ;

function CreateAccountValidator(req, res, next) {
  var config = [
    {
      name: 'username',
      type: 'post',
      validation: [
        {
          method: 'notEmpty',
          message: 'username is a required parameter'
        },
        {
          method: 'matches',
          message: 'username should only contain lowercase alpha numeric characters',
          args: [ '^[a-z0-9_\\-\\.]+$' ]
        }
      ]
    },
    {
      name: 'password',
      type: 'post',
      validation: [
        {
          method: 'notEmpty',
          message: 'password is a required parameter'
        }
      ]
    }
  ];

  Middleware.call(this, req, res, next, config);
}

util.inherits(Middleware, CreateAccountValidator);

module.exports = CreateAccountValidator;

Last, use the validation middleware in your express route definitions.

// app.js

var express = require('express')
  , validator = require('declare-validator')
  , app = express()
  ;

validator.init(app);

app.post('/account', CreateAccountValidator, controller.create);

With this set up, you would get an error with the following request:

POST /account
{
  "username": "bill murray!!"
}

Would return, using the default error formatter:

400 Bad Request
{
"errors": [
  {
    "param": "username",
    "message": "username should only contain lowercase alpha numeric characters",
    "value": "bill murray!!"
  },
  {
    "param": "password",
    "message": "password is a required parameter"
  }
]}

To Do / Think About

  • Terminology is very confusing here. The libraries themselves are all "validators" (express-validator, declare-validator, node-validator), the individual validation methods are known as validators (equals, isEmail, etc), and each middleware function we've created so far has been referred to as SomeValidator, which makes it much harder to quickly understand what's going on, would be nice to think that through a little.

  • Currently the way to create a validation middleware function is to create a function that util.inherits from the declare-validator function, and passes the config JSON as a parameter to Validator.call() ... which makes me wonder what the advantage of the declarative "config" approach is? Possible refactor would be to allow usage of the express-middleware functional toolset when defining Middleware functions, for cases where something more complex may be needed that the declarative style can't handle, etc.

These two are [x] DONE with the latest refactor :)

  • It seems like a lot of work to have to set up express-validator and declare-validator when this library could probably just wrap express-validator (and maybe even auto-include body-parser?). We need to think about the best way to do this.

  • Currently the only way to create a new validator method is to define it in lib/custom.js as a method on that exported object, which means you'll have to land your method in this library to use it, or modify it in node_modules. It would be much better if declare-validator had a method to add truly "custom" validator methods in a more bespoke way, adding on top of the extra validation methods that this library would provide long-term. (It'd be trivial to later add that method to this library if we determined it was general use enough.)