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

@sapphirejs/validator

v0.0.19

Published

Schema and Middleware Validator for Sapphire Framework

Downloads

3

Readme

Validator

A very thin wrapper on top of the fantastic Joi, mostly to provide simpler error handling and validator as middleware. If you know how to use Joi, than you'll feel right at home. Even if you don't, you're minutes away at pumping some awesome validation action.

Installation

$ npm install --save @sapphirejs/validator

Schema

Schemas are plain object literals with the field name as the key and a set of chained functions to declare validation rules. Let's see an example:

const { rule, Validator } = require('@sapphirejs/validator')

let validator = new Validator({
    name: 'John',
    email: '[email protected]',
    age: 27
  }, {
  name: rule.string().alphanum().required(),
  email: rule.string().email().required(),
  age: rule.number().min(18).max(200)
})

We've just input some data and a schema declaration for each of those inputs. Just remember that each validation should start with rule and move on with the chain of functions. Read more at the Joi API Documentation for the available data types and validation functions.

Now that we've run the validator, it exposes some properties to check if it failed or not:

validator.passes // true | false
validator.fails // true | false

Errors are returned in an object literal, so you can further process it or dump it directly as JSON output:

validator.errors
/*
ie: {
  name: ['"name" is required'],
  email: ['"email" is required', '"email" is not a valid email'],
}
*/

Middleware

Probably more interesting and streamlined than manually validating every request, middlewares can be injected into routes (or globally if that's what you need) and automate validation. They are very simple classes that declare the validation rules, while the rest is handled automatically.

Let's imagine we have a POST /users route where we send a body of parameters to create a new user.

app.post('/users', (req, res) => { /* handle user creation */ })

Next we build a UserValidator class that defines the validation rules:

const { ValidatorMiddleware } = require('sapphire-validator')

class UserValidator extends ValidatorMiddleware {
  rules() {
    return {
      name: 'John',
      email: '[email protected]',
      age: 27
    }
  }
}

And that's basically it. If we inject that class as a middleware, the request's body will be validated against those rules and a validator instance passed in the request object.

const UserValidator = require('./validators/uservalidator')

app.post('/users', new UserValidator().middleware, (req, res) => {
  if (req.validator.fails)
    res.status(422).json(req.validator.errors)

  /* handle user creation */
})

By default, the middleware will read req.body and req.query as input sources. If you need more control, like including req.params or cookies, you can always define your own fields() function inside a middleware class.

const { ValidatorMiddleware } = require('sapphire-validator')

class UserValidator extends ValidatorMiddleware {
  fields(req) {
    return {...req.body, ...req.params}
  }

  /* rules omited for brevity */
}

Or even manually define what fields you need:

const { ValidatorMiddleware } = require('sapphire-validator')

class UserValidator extends ValidatorMiddleware {
  fields(req) {
    return {
      name: req.body.name,
      age: req.query.age
    }
  }

  /* rules omited for brevity */
}