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

validation-middleware

v2.0.0

Published

Basic request middleware to sanitize and validate parameters, useful for express

Downloads

19

Readme

validation-middleware

NPM version NPM downloads Build Status

Flexible asynchronous validation middleware to sanitize and validate parameters at the same time. Based on validator.

Installing

npm install validation-middleware

Use

Which parameters does it receive? options, source = 'body', context = 'request'.

First param, options, this field is an object with the items you want to validate, e.g:

{
    _id: 'isMongoId',
    date: ['required', 'isDate'], // By default the parameters are not required
    website: {
        required: true,
        isUrl: {
            params: {           
                protocols: ['https'],
                require_host: true       
            }
        }
    }
}

The second param, source, it will tell middleware function where to find values to validate, by default it uses body key, but here you can find the same rules of the next item.

The third param, context, it will specify an object useful if you want to set your custom function and then have multiple options; those string values are allowed:

  1. context will return an object {request: ..., response: ..}
  2. request or response, by default we use request
  3. Any key in the request object.

Validators

Those are the available attributes for a validation stage.

{
    // Dot notation is allowed
    'field.name': { 
        <validation function name>:{
            // Everything here is optional 
            
            // It will be passes as parameters to the validation
            // function, if it needs more than 1 parameter
            // you should set an array
            params: <params>,
            
            // There's some custom messages, but you can specify it.
            message: "Custom message, {{campo}} reference to the filed name",
                                         ^
                                ----------
            as: "It replace 'campo' value",
            sanitize: {
                // Sanitize stages that will be called if validation passes
                // Same rules of validation are allowed here
            }
        }
    }
}

It's flexible because there's different ways to make a validation middleware, you can define custom functions too:

{
    email: ['required', 'isEmail'],
    name: 'required',
    'user.name': {
        required: true,                        // First validation stage
        custom: {                              // Second validation stage
            function(value, pattern, next){   
                return value.match(pattern)
            },
            params: /.*/ig
        },
        ...                                   // Other stages
    }
}

This is a list with the allowed validation function names, required validation stage is different, if it's set to false and the value from the source is empty the next stages are skipped.

Some functions have associated sanitizers functions by default:

  1. isBoolean
  2. isDate
  3. isInt
  4. isFloat
  5. isMongoId
  6. There's other sanitize function that could be assigned

If you want to avoid this behavior you should specify it, otherwise next middleware functions will get updated values:

{
    'product._id': {
        required: true,
        isMongoId: {
            sanitize: false
        }
    }
}

Error case

You can set your own error constructor, then an instance of this will be passed to the next express middleware

function ValidationError(message) {
    Error.call(this)
    this.message = message
}

Object.setPrototypeOf(ValidationError.prototype, Error.prototype);

require('validation-middleware').setHttpError({
    constructor: ValidationError
});

middleware = validator({
    email: ['required', 'isEmail']
});

app.get('/', middleware, function(request, response, err) {
    ...
})

app.use(function(request, response, next, error){
    error.should.be.instanceOf(ValidationError);
    error.should.be.instanceOf(Error);
    error.message.should.match(/The email must be a valid email address\./);
})

Example

let middleware = validator({
        'user.uuid': {
            required: false,
            custom: {
                function(value, options, next){
                    setTimeout(function () {
                        const maxLimit = options.maxLimit
                        next(value < maxLimit ? new Error('Range error') : '')
                    }, 1)
                },
                params: {
                    maxLimit: 10
                },
                required: false
            }
        },
        _id: 'isMongoId',
        email: {
            required: true,
            isEmail: {
                sanitize: {
                    normalizeEmail: {}
                }
            },
        },
    });

// request.body = {
//   user: {
//     uuid: '9'
//   },
//   _id: '51b14c2de8e185801f000006',
//   email: '[email protected]',
// }
app.get('/', middleware, function(request, response, next){
    // request.body = {
    //   _id: ObjectId('51b14c2de8e185801f000006'),
    //  email: '[email protected]' 
    // }
    //
});

TODO

  1. Add support for more languages.
  • en_US should have better error messages.
  • See validator and add more error messages for other functions.
  1. Support for custom params error.
  2. process.nextTick is called every 3 times, it should be customizable.