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

xapi-validator

v0.4.1

Published

Xapi Validator

Downloads

14

Readme

Xapi Validator

Build Status dependencies codecov

Xapi validator is one of the most advanced data validation library available. It allows you to define flexible rules to validate and filter parameters and various datatypes including complex object structures with recursive array and object level nesting.

★ Fully tested ★ Backend & browser ★ Flexible rule definitions ★ Custom filters ★ Custom validators ★

Sample

You can do complete validation for structures like this (more examples coming soon!):

{
  num: 1,
  str: '[email protected]',
  obj: {
    bool: false,
    substr: '[email protected]'
    arr: [
      {
        a: 2,
        b: true,
        c: {...}
      },
      {
        a: 3,
        b: false,
        c: {...}
      }
    ]
  }
}

With powerful field check rules like this:

{
  num: {
    default: 0,
    type: 'number',
    rules: [
      'validator:value=<5' // Value has to be less than 5
    ]
  },
  str: {
    type: 'string',
    rules: [
      'filter:length=16', // Longer strings are stripped from tail
      'validator:isEmail' // Must be email string
    ]
  },
  obj: {
    type: 'object',
    fields: {
      bool: {
        default: false,
        optional: true,
        type: 'boolean',
        rules: []
      },
      substr: 'str',    // Reference to 'str' field above,
      arr: {
        type: 'array',
        rules: [
          'each:subobj' // Each item is validated against 'subobj' rules
        ]
      }
    }
  },
  subobj: {
    a: 'num',
    b: 'obj.bool', // Reference to obj.bool field
    c: {
      type: 'object',
      ...
    }
  }
}

When data is run through the validator it not only checks that it adheres to the defined constrains, it will also produce the filtered output. For example you could use filter:xss in a string rule to get a safe version of the data on output:

validator.run('data', data);
> {errors: [], value: <filtered output>}

The module supports a vast range of different filters and validator functions natively, but allows your to define your own as well. To obtain a list of all natively supported filters and validators, run

validator.filters
validator.validators

Later versions will add support for search() where you can use fuzzy search to find suitable validator and filter functions. All natively supported filters and validators are already documented in the validator.strings object.

Examples

The library exports the Xvalidator object that takes three parameters:

import Xvalidator from 'xapi-validator';

var validator = new Xvalidator(
  <field rules>,         // Your validation rules
  <custom filters>,      // Supply your custom filter functions
  <custom validators>    // Supply your custom validator functions
)

The first parameter is your field rules ("schema"). A simple field rule definition could look like this:

var fields = {
  numField: {
    default: 0,
    type: 'number',
    rules: [
      'validator:number',         // This is implicitly called when 'type' is known
      'validator:value=-10,10'    // Value in range -10, 10
    ]
  }
}

Then you can initialize validator and validate fields

var validator = new Xvalidator(fields);
validator.run('numField', 1)
> {errors: [], value: 1}

validator.run('numField', 11)
> {errors: ['number not in specified range'], value: 11}

If your rules have filters, the input data is run through them sequentially. The result of run() will contain the filtered value in value property.

If run() returns no errors, then the filtered output in value can be trusted.

Filters

You can create your own filter functions and override native filters by giving your custom filter the same name. Here's an example filter:

custom: {
  params: ``,
  description: `filter that does nothing`,    // Description used in search()
  examples: ``,                               // Examples used in search()
  error: ``,                                  // Customize error message here
  call: (input, param1, param2) => {          // Filter function logic
    return input
  }
}

When defining custom filter functions, the call parameter points to the actual function executed when filtering. The first parameter to call should always be input - the data you wish to validate. You can have other parameters as well, they are used in field rules definitions like this:

...
rules: [
  'filter:custom=param1,param2'
]

Validators

You can create your own validator functions and override native validators by giving your custom validator the same name. Here's an example validator:

custom: {
  params: ``,
  description: `validator that does nothing`,    // Description used in search()
  examples: ``,                               // Examples used in search()
  error: ``,                                  // Customize error message here
  call: (input, param1, param2) => {          // Validator function logic
    return true
  }
}

Like with filters as described above, validators can receive parameters. Validator functions should always return either true (validated OK) or false (validation FAILED);

Object validation

By default, each field in object rule checker is required. You can override this by settings them as optional:

obj: {
  type: 'object',
  fields: {
    a: {
      type: 'string',
      optional: true
    }
  }
}

Optional fields are not run through checks if their type is undefined (not present in the input data). Othewise the checks are run.

Object fields that are not defined in field checks rules are automatically ommited.

License

MIT License

Copyright (c) 2017 Andreas Urbanski

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.