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

credible

v0.2.2

Published

Unopinionated validation framework for node and the browser.

Downloads

21

Readme

credible

NPM version Build Status

Credible is a library for validating objects in node.js or the browser. While it provides several validators out of the box, credible is very unopinionated; mostly, credible simply provides a framework for object validation.

Installation

Credible has one dependency: An A+ promise library, i.e. bluebird or when.js.

Node.js

$ npm install credible --save

Node takes care of the dependency automatically.

Browser

<script src="/bluebird.js"></script>
<script src="/credible.min.js"></script>

By default, Credible uses bluebird; to use a different implementation, set Credible.Promise to the correct library.

Usage

var rules = {
  name: {
    presence: true
  },
  email: {
    email: true
  }
}

var obj = {
  name: 'Noah Portes Chaikin',
  email: '[email protected]'
}

var credible = new Credible(rules)
  .run(obj)
  .catch(function (errors) {
    console.log(errors.toJSON());
  })

See examples.

API

Every method in a Credible instance returns the instance except credible.run(), which returns a promise.

new Credible(arguments..)

The main Credible constructor optionally accepts the same arguments as credible.rule() (see below).

credible.rule(arguments..)

Used to set new rules. credible.rule() is a variadic function; it accepts any of the following sets of arguments:

credible
  .rule(properties, validator, options)
  .rule(properties, { validator1: options, validator2: options })
  .rule(validator, options)

validator is either an available validator or a function. To use an available validator, simply pass the validator's name as a string or an object key:

credible
  .rule('name', 'presence', true)
  .rule('name', { length: { greaterThan: 5 } })
  .rule(['firstName', 'lastName'], { length: { greaterThan: 5 } })
  .rule({ name: { presence: true }, email: { email: { if: function (obj) { return obj.email; } } } })

On validation, a validator function is passed the object, the property key (if provided), and options. Validator functions can return promises for asynchronous validation. This is an example validator:

var emailValidator = function (object, property, options) {
  if ( /^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,6}$/i.test(object[property])) {
    throw property + ' is an invalid e-mail address';
  }
}

Validators can be sent any number of settings in the options object; the following options are made available to every validator and are handled by the credible object:

| Key | Description | | --- | ----------- | | if: fn | Only validate if fn returns true. fn is a function; the object being validated is passed to fn as an argument. | | unless: fn | Only validate if fn returns false. fn is a function; the object being validated is passed to fn as an argument. | | invalid: fn | fn is a function to handle a failed validation; the object being validated is passed to fn as an argument. |

credible.if([properties], fn)

Only run validator if fn (a function) returns true. fn is passed the object being validated. Optionally, passing properties will only execute the test on validators executed on the specified properties.

credible
  .if(function (object) {
    return object.foo == 'bar';
  });

credible
  .if('name', function (object) {
    return object.foo == 'bar';
  });

credible
  .if(['firstName', 'lastName'], function (object) {
    return object.foo == 'bar';
  });
credible.unless([property], fn)

Only run validator if fn (a function) returns false. fn is passed the object being validated. Optionally, passing properties will only execute the test on validators executed on the specified properties.

credible
  .unless(function (object) {
    return object.foo == 'bar';
  });

credible
  .unless('name', function (object) {
    return object.foo == 'bar';
  });

credible
  .unless(['firstName', 'lastName'], function (object) {
    return object.foo == 'bar';
  });
credible.invalid([property], fn)

Pass fn, a function, for handling a failed validation. fn is passed the object being validated. Optionally, passing properties will only execute the function for failed validations executed on the specified properties.

credible
  .invalid(function (object) {
    throw 'This object is invalid.';
  });

credible
  .invalid('name', function (object) {
    throw 'This name is invalid.';
  });

credible
  .invalid(['firstName', 'lastName'], function (object) {
    throw 'This name is invalid.';
  });
credible.run(object)

Run validations on object; returns a promise.

credible
  .run(obj)
  .then(function () {
    console.log('It\'s valid!');
  })
  .catch(function (errors) {
    console.log(errors.toJSON());
  })

Available Validators

alpha

Property must contain only letters.

alphaNumeric

Property must contain only letters and numbers.

alphaNumericDash

Property must contain only letters, numbers and dashes.

alphaNumericUnderscore

Property must contain only letters, numbers and underscores.

array

Property must be an array.

boolean

Property must be a boolean (true or false only).

contains

Property must contain the string specified in the second argument.

date

Property must be a date (Date object).

email

Property must be a valid e-mail address.

exists

Property must exist (not be undefined).

fn

Property must be a function.

in

Property must be in specified array.

credible
  .rule( { state: { in: ['approved', 'pending'] } } );

integer

Property must be an integer.

json

Property must be a valid JSON string.

length

Property must have a length matching specifications set in options.

Options

| Key | Description | | --- | ----------- | | greaterThan: number | Property must have a length greater than number | | lessThan: number | Property must have a length less than number | | greaterThanOrEqualTo: number | Property must have a length greater than or equal to number | | lessThanOrEqualTo: number | Property must have a length less than or equal to number | | equalTo: number | Property must have a length equal to number |

lowercase

Property must contain all lowercase letters.

luhn

Property must be a valid credit card number.

matches

Property must match RegExp object specified in second argument.

natural

Property must be a positive number.

naturalNonZero

Property must be a positive number greater than zero.

NaN

Property must not be a number (isNaN(value) returns false).

number

Property must be a number.

presence

Property must be defined and not empty.

object

Property must be an object.

operator

Compare property to a number or another property set in options.

Options

| Key | Description | | --- | ----------- | | greaterThan: numberOrProperty | Property must have a length greater than numberOrProperty | | lessThan: numberOrProperty | Property must have a length less than numberOrProperty | | greaterThanOrEqualTo: numberOrProperty | Property must have a length greater than or equal to numberOrProperty | | lessThanOrEqualTo: numberOrProperty | Property must have a length less than or equal to numberOrProperty | | equalTo: numberOrProperty | Property must have a length equal to numberOrProperty |

regexp

Property must be a regular expression (RegExp object).

string

Property must be a string.

uppercase

Property must contain all uppercase letters.

url

Property must be a valid URL.

License & Contributing