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

bq-validator

v1.0.0

Published

Validate fields for requests

Downloads

5

Readme

Codeship Status for RobCatch/bq-validator Code Climate Test Coverage

bq-validator

Middleware to validate fields given in requests to an express app

Usage

The first parameter defines the fields that are required. In the example below, a request to the login api would require a username and a password. The second parameter is a callback function that is called if any missing or invalid fields are found. This function is passed a message describing what fields are missing.

The required fields can contain nested operators for conditional fields.

var validate = require('bq-validator');
app.use('api/users/login', validate({ $and: [ 'username', 'password' ] }, function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

Giving an array is a shorthand for doing $and, so { $and: [ 'username', 'password' ] } here could just be [ 'username', 'password' ] instead.

Available Operators

$or

Checks that at least one of the fields are given.

// array of validations, where only one element must be validated
app.use('api/users/login', validate([
    { $or: [
      'email',
      'username',
    ] },
    'password'
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: "Missing login credentials!"
  })
})
// object of validations, where only one key must be validated
app.use('api/events/create', validate({
  $date: 'start',
  $or: {
    $date: 'finish',
    $number: 'occurences'
  } 
}, function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: "Don't know when the event ends!"
  })
})

$and

Checks that all the fields are given. The same can be achieved by just using an array however.

app.use('api/location/create', validate({
  $or: [
    { $and: [
      "lat",
      "long"
    ] },
    "address"
  ] 
}, function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

// the required fields here could just be
{ 
  $or: [
    [ "lat", "long" ],
    "address"
  ]
}

$query, $body

The middleware will check the fields in either req.query or req.body, depending on the request method. This can be overiden for specific fields using $query and $body. In the example below, an appKey must be passed as a query parameter, with either a name or description in the request body (presuming this is a PUT request).

app.use('api/app/update', validate({
  $query: 'appKey',
  $or: [
    'name',
    'description'
  ]
}, function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

$number

Checks that a field is a number, and converts it from a string.

app.use('api/counter/update', validate({
  $number: 'count'
}, function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: "Count is required".
  })
})

$int

Checks that a field is an integer, and converts it from a string.

app.use('api/event/create', validate([
  "name",
  "location",
  { $number: 'attendence' }
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

$boolean

Checks that field is a boolean value, true or false, and converts it from a string.

app.use('api/event/create', validate([
  "name",
  "location",
  { $boolean: 'private' }
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

$date

Checks that a field is a date, and converts it from a string into a Date object.

app.use('api/event/create', validate([
  "name",
  "location",
  { $date: date }
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

$email

Checks that a field is a valid email address.

app.use('api/user/login', validate([
    { $or: [
      { $email: 'email' },
      'username',
    ] },
    'password'
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

$json

Checks that a field is a JSON string, and converts it into an object.

app.use('api/event/query', validate({
  $json: 'where'
}, function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: "Query must have where clause in JSON format"
  })
})

Multiple fields of a type

An array can be given to check mutliple fields for operators that check for a specific value type. The example below shows two dates required to create and event.

app.use('api/event/create', validate([
  "name",
  "location",
  { $date: [ 'start', 'end' ] }
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

Custom Validation

Fields can be checked to match a specific set of values. To do this, use an object containing the field name as a key, and an array to match against as the corresponding value. The array can contain strings or regular expressions. If a regular expression is used then the field will be set to the result of match.

app.use('api/car/create', validate([
  { color: ['red', 'blue', 'green', 'black', 'white', /^#([A-Fa-f0-9]{6})$/] },
  'make',
  'model'
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})

Using a function. The value of field given with the request is passed to the function. If the field is not given then it will fail automatically. If the validation is failed, then the function should have no return value. This is done so that you can return a value to set for the field.

// Turn a field into a mongo ObjectID
var ObjectID = require('mongodb').ObjectID;
app.use('api/character/add', validate({
  id: [ function(value){
    try {
      return ObjectID(value);
    } catch(err) {
      // error will be thrown if it's not valid
      // no return value means validation failed
    }
  } ]
}, function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: "id is required"
  })
})

// Only allow dates after 2015-01-01
// Since $date occurs first, the value will already be a Date object
// If no date was given, or it was invalid, the value will be undefined and verification will fail automatically.
// Note the value must be returned.

app.use('api/reminder/create', validate([
  'title',
  'description',
  {
    $date: 'date',
    date: [ function(value){
      if(value > new Date('2015-01-01')){
        return value;
      }
    } ]
  }
], function(missing, req, res){
  res.status(400).json({
    status: 400,
    message: missing
  })
})