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

validr

v0.1.6

Published

Validations without ties to any framework. Inspired by validator, express-validator and validictorian.

Downloads

39

Readme

Validr

Build Status

Framework agnostic Node.js validations. Inspired by validator, express-validator and validictorian.

Installation

npm install validr

Usage

If you have ever used express-validator you should feel right at home.

Here is an example using Express. Can be used similarly in any other framework.

var express = require('express'),
  Validr = require('validr'),
  trimBody = require('trim-body');

app = express();

app.use(express.bodyParser());
app.use(app.router);

app.post('/user', function (req, res){
  trimBody(req.body);

  // Expected 'req.body' object format
  // {
  //   name: {
  //     first: <first name>,
  //     last: <last name>
  //   },
  //   email: <email>,
  //   age: <age>,
  //   sex: <sex>,
  //   occupation: <occupation>
  // }


  // 1. Create an instance of Validr.

  var validr = new Validr(req.body);


  // 2. Validations

  validr
    // use string with dot-notation to validate nested fields
    .validate('name.first', 'First Name is required.')
    .isLength(1);

  validr
    // you can also use an array to validate nested fields
    .validate(['name', 'last'], 'Last Name is required.')
    .isLength(1);

  validr
    // an object can be used to set separate validation messages for validators.
    .validate('email', {
      isLength: 'Email is required.',
      isEmail: 'Email must be valid.'
    })
    // validators are chainable
    .isLength(1).isEmail(); 

  validr
    // validate method accepts a 3rd parameter which is an options object
    // age will not be validated if '', `null` or undefined
    .validate('age', 'Age must be a number.', {ignoreEmpty: true})
    .isNumeric();

  validr
    .validate('sex', 'Sex must be M (male) or F (female).')
    .isIn(['M', 'F']).isLength(1);


  // 3. Check for errors.

  var errors = validr.validationErrors();

  if (errors) return res.json(errors);



  // ...
  // Process req.body however you want. Example: save to db.
});


app.listen(3000);

Validate

Validating fields is similar to express-validator's assert.

Differences between validate and assert.

  • No notEmpty and len methods. Use isLength.
  • Nested fields are targeted with a dot-notation string or array. Example: 'name.first' or ['name', 'first'].

You can pass a 3rd parameter to validate to ignore validation if field is not supplied. See usage's age validation

Validation errors

You can get errors in two ways. Similar to express-validator.

var errors = validr.validationErrors();
var mappedErrors = validr.validationErrors(true);

errors:

[
  {param: "email", msg: "Email is required.", value: "<received input>"},
  {param: "email", msg: "Email must be valid.", value: "<received input>"},
  {param: "age", msg: "Age must be a number.", value: "<received input>"}
]

mappedErrors:

{
  email: {
    param: "email",
    msg: "Email must be valid.",
    value: "<received input>"
  },
  age: {
    param: "age",
    msg: "Age is required.",
    value: "<received input>"
  }
}

Extending with custom validators

Add custom validator functions to an object, which is the second parameter when instantiating Validr.

var validr = new Validr(body, {
  isNotExampleEmail: function(str) {
    return !/@example.com/.test(str);
  }
});

validr.validate('email', {
  isLength: 'Email is required.',
  isEmail: 'Email must be valid',
  isNotExampleEmail: 'Email must NOT be @example.com.'
  }).isLength(1).isEmail().isNotExampleEmail();

Tests

npm install -g mocha

Then,

npm test

Contributors

License

MIT