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

iz

v3.0.0

Published

Validation for node and the web.

Downloads

2,979

Readme

Build Status

What is it?

A validation library written for client/server side needs in javascript.

Setup

Installation

npm install iz --save
# or
yarn add iz

Then you can include iz, are and validators if needed

import iz from 'iz';
import are from 'iz/lib/are';
import validators from 'iz/lib/validators';

Once you do this, you can start validating. To do this, provide a value, any associated error messages and the validators. Here is a simple example:

import iz from 'iz';
import validators from 'iz/lib/validators';

iz({ value: 'Test', errorMessages: { string: 'Must be a string' }, validators}).string().valid;

If you'd like to do something more custom (to reduce bundle size):

import iz from 'iz';
import between from 'iz/lib/basicValidators/between';
import int from 'iz/lib/basicValidators/int';

function myCustomValidator { ... }

iz({ value: 4, validators: { between, int, myCustomValidator }}).string().valid;

Requirements

Iz v2+ heavily relies on many es6 features including: promises, proxies, objects and arrays. You MUST polyfill proxy and promise, the other features will compile to es5. If something doesn't work please report it.

API

Chaining:

iz({ value: 10, validators }).between(2, 15).int().multiple(5); // why yes, yes it is
iz({ value: 10, validators }).notBetween(1, 5); // all validators (custom or not) have a not variant available

iz(), and all validation commands return an Iz object. An iz object always contains an errors{array} and valid{bool}. errors will be filled with a default error messsage for each incorrect field. To provide custom error messages you can do the following:

var customErrorMessages = {
    notBetween: 'Value must be between!',
    int: 'Not an int!!!',
    multiple: 'This is terrible and you should fix it'
}
iz({ value: 'Bob', errorMessages: customErrorMessages }).notBetween(2, 15).int().multiple(5);

JSON

It is often useful to get a list of validations from your server for a given model. Nested objects work to!

var rules = {
    'cost': [
        {
            'rule': 'between',
            'args': [17, 1000],
            'error': 'The cost must be between 17, 1000'
        },
        {
            'rule': 'required',
            'error': 'You must specify a cost'
        },
    ],
    'producer.id': [
        {
            'rule': 'int',
            'error': 'Producer ID must be an int'
        }
    ],
    'producer.name.first': [
        {
            'rule': 'alphaNumeric',
            'error': 'Must be names and numbers'
        }
    ]
};

are(rules, validators).for({
    cost: 20,
    producer: {
        id: 1,
        name: {
            first: 'bob'
        }
    }
}).valid;

It is often useful to get back error messages from an Are object. You can use the "invalidFields" property to get back errorMessages.

var result = Are(...).for(someAttributeObject);

if (!result.valid) {
    return rules.invalidFields;
}

Async Validations

You can create custom validations that run asynchronously. This works with both iz and are functions. IMPORTANT: If you have an async validator and don't use the async property, you'll get false positives.

const validators = {
    unique: function() {
        return fetch(...).then(() => true).catch(false);
    }
};

iz({ value: 'name', validators }).unique().async.then((result) => {
    result.valid; // can be true or false;
})

// we also support async/await
let result = await iz({ value: 'name', validators }).unique().async;
return result.valid;

let result = await are(...).for(obj).async;
return result.valid;

Error Messages:

In the event you want to return more detailed error messages. You can use a simple syntax to format your error message with a validators arguments.

var errorMessages = {between: '{{0}} is not between {{1}} and {{2}}'};
var izObj = iz({ value: 5, errorMessages, validators }).between(100, 200);
console.log(izObj.errors);

will log ['5 is not between 100 and 200']. This works with are.getInvalidFields() too.

Required Fields:

In most cases, you'll only want to validate values when they exist. By default iz functions in this way. If you want to force the presence of a value you can use the required method.

iz({ value, validators }).required() //a value is required
iz({ value, validators }).email().required() //value is required and is a valid email
iz({ value, validators }).date() //value is not required but must be a date if provided

Validators:

All validators (apart from iz.required) return true if no value is provided (e.g. null, undefined or '').

Validations (true case in comments):

alphaNumeric(*);               // Is number or string(contains only numbers or strings)
between(number, start, end);   // Number is start or greater but less than or equal to end, all params numeric
blank(*);                      // Empty string
boolean(*);                    // true, false, 0, 1
cc(*);                         // Luhn checksum approved value
date(*);                       // Is a date obj or is a string that is easily converted to a date
decimal(*);                    // int or float
email(*);                      // Seems like a valid email address
empty(*);                      // If an object, array or function contains no properties true. All primitives return true.
equal(*, *);                   // Any 2 things are strictly equal. If 2 objects their internal properties will be checked. If the first parameter has an equals method that will be run instead
extension(ob1, ob2);           // If obj2's methods are all found in obj1
fileExtension(value, arr);     // Checks if the extension of value is in arr. An obj can be provide, but must have indexOf defined.
fileExtensionAudio(value);     // Check against mp3, ogg, wav, aac
fileExtensionImage(value);     // Check against png, jpg, jpeg, gif, bmp, svg, gif
inArray(value, arr);           // If * is in the array
anArray(arr);                  // If arr is an array
int(*, bool (optional));       // Is an int. If the 2nd variable is true (false by default) a decimal is allowed
ip(str);                       // str resembles an IPV4 or IPV6 address
minLength(val, min);           // val (str or arr) is greater than min
match(str, tester, flags?);    // RegExp matching of a string. Accepts RegExps and strings as the tester
maxLength(val, max);           // val (str or arr) is shorter than max
multipleInt(num, mult);        // Int is multiple of another Int
multipleFloat(num, mult);      // Float is multiple of another Float
number(*);                     // Is either an int or decimal
ofType(obj, typeName);         // If it is a named object, and the name matches the string
phone(str, canHaveExtension?); // Is an american phone number. Any punctuations are allowed.
postal(*);                     // Is a postal code or zip code
required(*);                   // Is not null, undefined or an empty string
ssn(*);                        // Is a social security number
string(*);                     // Is the argument of type string

Almost all possible use cases that will definitely work (and definitely not work) are in the spec folder.

TODO

Add nested error rules within are. The current implementation doesn't allow for composition.

Change Log

3.0.0

Goal: Allow for singleton free creation of Iz and Are objects. This is not a backwards compatible change. Many systems these days don't play nicely with singletons especially due to code splitting. This change should resolve that problem by required that Iz objects be supplied with validators. This also required the ordering of arguments supplied to Iz be modified. Click here for docs on the old "register" system if you're using v2.

Summary:

  • Validators are passed into every call to iz and are. This makes Iz more portable/flexible.
  • Added a "multipleFloat" validator.
  • Renamed "multiple" into "multipleInt"
  • Dropped support for "register"

2.3.1

  • Fix up security vulnerabilities as reported by Github

2.2.4

  • Issue #44 - Iz should be proxy polyfill compatible (IE11 support)

2.2.3

  • Issues #41/#42 - izEqual should accept null values

2.2.1

  • Bug fixes
  • Unit tests are stricter
  • Email validation is vastly improved

2.1.0

  • Added RegExp (match) validation

2.0.0

Goals - Modernize, make the library smaller and add more features.

New features:

  • Async/Await and Promise based validations.
  • Better email validator

Improvements:

  • Only import the validators you need
  • Simplified creation of Iz/Are objects
  • ofType validator now accounts for minification

Other:

  • Switched not validations from .not().xyz() to notXYZ format to reduce library size.
  • Changed API for Iz
    • Removed "setValue" and revalidation methods
  • Required validations
    • They no longer apply on the validation function but work through iz and its proxy
  • Changed API for Are
    • Dropped iz validations mixed with are validations. Are only supports JSON now.
    • Removed revalidation and setValue methods
  • Trimmed docs, it was getting complicated for no reason

0.7.0

  • Added iz.addValidator method to add custom validations more effectively

0.6.0

  • Added is.anArray validation

0.5.2

  • Removed a strange hidden character that was introduced

0.5.0

  • Added interpolation to error messages
  • Added bower
  • Changed license and copyright info
  • Fixed readme typos

0.4.1

  • Changed AMD compile process
  • Rebuilt modules as AMD
  • Split out tasks into their own files
  • Added roadmap
  • Fixed up more docs

0.4.0

  • Renamed private _fields variable in Are to fields
  • Added getInvalidFields to Are
  • Added iz.string validation
  • Fixed docs

0.3.0

  • Added JSON based validations
  • Replaced previous build system with requirejs.
  • Doc simplification
  • Code style reformatting

0.2.0

  • Added iz.required()
  • Falsy values now pass through as valid without .required

0.1.0

  • Fixed loading of iz, are and validator modules
  • Added missing 'blank' validator
  • Added build/test system via grunt
  • Removed versions in bin
  • Added version/generation number in banner
  • Changed file structure

0.0.4

  • Revalidation was added to iz
  • Add are() for group validation
  • Clean-up of syntax/optimizations

0.0.3

  • Added equal method
  • Added empty method
  • Added not() operation

0.0.2

  • Re-ordered parameters for fileExtension and inArray
  • Added method chaining
  • Added error messages