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

validate.it.js

v0.1.3

Published

simple way to validate

Downloads

7

Readme

validate.it.js

Simple way to validate

Installation

install from npmjs

npm install --save validate.it.js

and import in preffered style

import validate from 'validate.it.js';
const validate = require('validate.it.js');

Or just download last version from releases page and add script tag in end of body

<script src="/validate.it.js"></script>

validate variable will be in global scope

Usage

Give him a string and call needed asserts

validate('Pa$$w0rd')
  .hasLettersLatin()
  .hasNumbers()
  .has("!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+");
// -->
{
  ok: true,
  base: 'Pa$$w0rd',
  asserts: ['hasLettersLatin', 'hasNumbers', 'has'],
  errors: []
}
validate('bob')
  .hasLettersLatin()
  .hasNumbers();
// -->
{
  ok: false,
  base: 'bob',
  asserts: ['hasLettersLatin', 'hasNumbers'],
  errors: [
    {
      path: [],
      rule: 'hasNumbers',
      details: {
        string: 'bob',
        subStrings: ["1","2","3","4","5","6","7","8","9","0"],
        found: false,
        message: '"bob" has no numbers'
      }
    }
  ]
}

API

validation - is a function of single argument called base. It returns result described below. Result has methods called asserts, which returns mutated result - so you can call chains of asserts. Like

result = validation( base )
  .assert()
  .anotherAssert( argument )
  .yetAnotherAssert( set, of, arguments );

Note

Asserts combined in AND logic way. So if any of asserts fails - validation fails.

  • Result - result of validation in clean readable format.
  • Assert - step of validation process. It checks base by specified rule.
  • .extend - static method allows you to add your own asserts.

Result

result is just an object with params:

  • ok bool - status of validation
    • true - validation passed
    • false - validation fails
  • base string|varios - basis for validation
    • right now validate.it works only with simple string bases. But if you know why and how to use it with other types of values - we can implement it.
  • asserts array - called asserts names in call order
  • errors array - Validation Reports for failed asserts

simpliest result you can get by calling validation without any assert

validate('')
// -->
{
  ok: true,
  base: '',
  asserts: [],
  errors: []
}

Validation Report

"Unified validation report interface" - @rumkin / Validation Report . git

This is a DTO used as error objects in errors array. Every VR contains:

  • path array - empty array []
  • rule string - name of assert
  • details object - object with non-stardartized params describes reason of failure.
    • details.message string - enduser oriented error description.

Example

{
  path: [],
  rule: 'hasNumbers',
  details: {
    string: 'bob',
    subStrings: ["1","2","3","4","5","6","7","8","9","0"],
    found: false,
    message: '"bob" has no numbers'
  }
}

Asserts

.has

Check that any subString present in base.

Syntax:

.has( subString [, subString2...] )

Fail details:

{
    string: base,
    subStrings: [subString, subString2...],
    found: false,
    message: 'not any of ["subString", "subString2"...] found in "base"'
}

Examples:

validate('abc123').has('a').ok === true;
validate('abc123').has('c1','e4').ok === true;

validate('abc123').has('d').ok === false;
validate('abc123').has('e2','e4').ok === false;

.hasNo

Check that any subString unpresent in base.

Syntax:

.hasNo( subString [, subString2...] )

Fail details:

{
    string: base,
    subStrings: [subString, subString2...],
    found: true,
    message: 'every of ["subString", "subString2"...] found in "base"'
}

Examples:

validate('abc123').has('e').ok === true;
validate('abc123').has('c1','e4').ok === true;

validate('abc123').has('b').ok === false;
validate('abc123').has('a','b','c').ok === false;

.hasNumbers

Check that any number present in base.

Syntax:

.hasNumbers()

Fail details:

{
    string: base,
    subStrings: ["1","2","3","4","5","6","7","8","9","0"],
    found: false,
    message: '"base" has no numbers'
}

Examples:

validate('abc123').hasNumbers().ok === true;

validate('abc').hasNumbers().ok === false;

.hasLettersLatin

Check that any latin letter present in base.

Syntax:

.hasLettersLatin()

Fail details:

{
    string: base,
    subStrings: ["a","b","c", ... "X","Y","Z"],
    found: false,
    message: '"base" has no latin letters'
}

Examples:

validate('abc123').hasLettersLatin().ok === true;

validate('123').hasLettersLatin().ok === false;

.match

Check base for matching any regexp.

Syntax:

.match( regexp [, regexp2...] )

Fail details:

{
    string: base,
    patterns: ['pattern', 'pattern2'...],
    match: false,
    message: '"base" don\'t match any of ["pattern", "pattern2"...]'
}

Examples:

validate('abc123').match(/\d/).ok === true;
validate('abc123').match(/^a.*3$/).ok === true;

validate('abc123').match(/\s/).ok === false;
validate('abc123').match(/\s/, /def456/).ok === false;

.length

Check that length of base is equal to lengthRequired.

Syntax:

.length( lengthRequired )

Fail details:

{
    string: base,
    length: 4,
    lengthRequired: 3,
    message: 'length of "base" is not equal to 3'
}

Examples:

validate('abc').length(3).ok === true;
validate('').length(0).ok === true;

validate('abc').length(4).ok === false;
validate('abc123').length(3).ok === false;

.lessThan

Check that length of base is less than lengthBeyond.

Syntax:

.lessThan( lengthBeyond )

Notice: lengthBeyond must be a positive Number

Fail details:

{
    string: base,
    length: 4,
    lengthBeyond: 3,
    message: 'length of "base" is not less than 3'
}

Examples:

validate('abc').lessThan(4).ok === true;
validate('').lessThan(1).ok === true;

validate('abc').lessThan(3).ok === false;
validate('abc123').lessThan(3).ok === false;

.longerThan

Check that length of base is longer than lengthBeyond.

Syntax:

.longerThan( lengthBeyond )

Fail details:

{
    string: base,
    length: 4,
    lengthBeyond: 5,
    message: 'length of "base" is not longer than 5'
}

Examples:

validate('abc').longerThan(2).ok === true;
validate('abc').longerThan(0).ok === true;

validate('abc').longerThan(3).ok === false;
validate('abc').longerThan(5).ok === false;

.eval

Calls function assert with base as only argument. Fails if it returns something. Syntax:

.eval( assert )

Any return of assert (except of undefined) will be converted into details object and wrapped with Validation Report. Simple strings will be placed as .message property:

'no smiles found' -> {mesage: 'no smiles found'}

other results will be converted as is:

{a: 1, b: '2'} -> {a: 1, b: '2'}

[1, 2, 3] -> {0: 1, 1: 2, 2: 3}

true -> {}

Function -> {}

Examples:

validate('abc123').eval(() => {}).ok === true;
validate('abc123').eval(base => base === ':)' : 'found you' ? undefined).ok === true;

validate('abc123').eval(() => true).ok === false;
validate('abc123').eval(() => 'some text').errors[0].details;
// -->
{
  message: 'some text'
}
validate('abc123').eval(() => {some: 'text'}).errors[0].details;
// -->
{
  some: 'text'
}

Extend

Static method allows you to add your own asserts. It adds assert to list of asserts by name. Syntax:

validation.extend( name, assert );

assert is function with same behaviour as it in .eval( assert ). It should return nothing (undefined) if assert pass and any other value otherwise.

One powerfull difference - it can take arguments besides base Example:

validate.extend('hasSmile', (base, australian) => {
    const smiles = [':)', ':(', ';)'];
    const australianSmiles = ['(:', '):', '(;'];
    const checkSmiles = australian ? australianSmiles : smiles;
    const smileFound = checkSmiles.some(smile => base.includes(smile));
    if (smileFound)
        return;
    
    return `no smiles in "${base}"`;
});
validate('hello :)').hasSmile().ok === true;
validate('hello (:').hasSmile(true).ok === true;

validate('hello').hasSmile().ok === false;
validate('hello').hasSmile().errors[0].details;
// -->
{
  message: 'no smiles in "hello"'
}

Psst.. Do not use it a lot. Contribute instead!

Contribute

You know another usefull assert? Fill free to pull request here.

Check the Contributers guide