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

semantic-validator

v0.1.1

Published

A functional semantic validator tool for validation of several types and rich content.

Downloads

5

Readme

Semantic Validator

A functional semantic validator tool for validation of several types and rich content, inspired by prop-types from React.

npm version Build Status Coverage Status

Get started

Using NPM or Yarn

First, install it via npm.

npm i semantic-validator

Then, import it from dependencies and enjoy it.

import { op, is } from 'semantic-validator';

const validate = op.shape({
  id: is.integer(),
  tags: op.every(is.string()),
});

Using script tag

First, add a script tag with to the HTML page.

<script src="https://unpkg.com/semantic-validator/bundle.js" crossorigin></script>

Then, just enjoy it.

var op = semanticValidator.op;
var is = semanticValidator.is;

var validate = op.shape({
  id: is.integer(),
  tags: op.every(is.string())
});

Usage

The base unit of the semantic validator is a function which accepts the value as an argument for validation. We define it in TypeScript like below.

type Validator<T = any> = (val: T) => boolean;

This validator tool has several methods in two types: validator operator (op) and validator creator (is).

For example, we can call a validator creator such as is.integer() to create a validator which expects the number should be an integer. We can also call is.greaterThan(100) to create a validator which expects the number is greater than 100.
If we want to match both conditions, we can use a validator operator like op.and(validator1, validator2) to combine two validators.

import { op, is } from 'semantic-validator';

const isInt = is.integer();
isInt(12); // => true;
isInt(12.34); // => false;

const isGt100 = is.greaterThan(100);
isGt100(150); // => true;
isGt100(50); // => false;

const isIntGt100 = op.and(
  is.integer(),
  is.greaterThan(100),
);
isIntGt100(123); // => true;
isIntGt100(123.456); // => false;
isIntGt100(12); // => false;

You can also integrate other validation tools together. Just follow the validator pattern.

For example, there is a method isUUID(str, version) for validating a string. We can make a validator like val => isUUID(val, 5) and compose with other validator operators.

import { op, is } from 'semantic-validator';

const validate = op.shape({
  id: (val => isUUID(val, 5)),
  name: is.string(),
});
validate({ id: '6fad3a7b-161b-5e10-b265-8d522f3f35b5', name: 'Agent K' }); // => true;
validate({ id: 'abc', name: 'Agent K' }); // => false;

Cheatsheet

| Method | Description | | ---------------------------------------------------------------- | ---------------------------------------------------------------- | | Basic validator operators | | | > op.so(validator) | Pass the validator. | | > op.not(validator) | Not pass the validator. | | > op.and(...validators) | Pass all validators. | | > op.or(...validators) | Pass any validators. | | > op.every(validator) | Pass the validator on all elements in an array. | | > op.some(validator) | Pass the validator on any elements in an array. | | > op.shape({ ...validatorOfKeys }) | Pass all validators for each properties of an object. | | > op.exact({ ...validatorOfKeys }) | Pass all validators for each properties of an exact object. | | Converter validator operators | | | > op.convert(converter, validator) | Pass the validator after converted. | | > op.toFloat(validator) | Pass the validator after converted to a float. | | > op.toInteger(validator) | Pass the validator after converted to an integer. | | > op.toLength(validator) | Pass the validator after converted to the length. | | > op.toSplit(separator, validator) | Pass the validator after splitted the string as an array. | | > op.toKeys(validator) | Pass the validator after converted to keys of an object. | | > op.toValues(validator) | Pass the validator after converted to values of an object. | | > op.toDate(validator) | Pass the validator after converted to a date object. | | Basic validator creators | | | > is.same(value) | Is the same as the base value? | | > is.oneOf(...values) | Is the same as any base values? | | > is.defined() | Is defined (not undefined)? | | > is.notDefined() | Is undefined? | | > is.nul() | Is null? | | > is.nil() | Is undefined or null? | | > is.bool() | Is a boolean? | | > is.number() | Is a number? | | > is.string() | Is a string? | | > is.object() | Is a non null object? | | > is.func() | Is a function? | | > is.symbol() | Is a symbol? | | > is.instanceOf(constructor) | Is an instance of the constructor (class)? | | > is.float() | Is a valid (not NaN or Infinity) float? | | > is.integer() | Is a valid (not NaN or Infinity) integer? | | > is.array() | Is an array? | | > is.date() | Is a valid (not Invalid Date) date object? | | Math validator creators | | | > is.equalTo(num) | Is the number equal to the base number? | | > is.greaterThan(num) | Is the number greater than the base number? | | > is.atLeast(num) | Is the number at least the base number? | | > is.lessThan(num) | Is the number less than the base number? | | > is.atMost(num) | Is the number at most the base number? | | > is.between(min, max) | Is the number between the base numbers? | | > is.fromTo(min, max) | Is the number from and to the base numbers? | | Text validator creators | | | > is.match(regexp) | Is the string match the regular expression? | | > is.startsWith(wording) | Is the string starts with the wording? | | > is.endsWith(wording) | Is the string ends with the wording? | | > is.contains(wording) | Is the string contains the wording? | | List validator creators | | | > is.includes(...includings) | Is the array includes all includings? | | > is.excludes(...excludings) | Is the array excludes all excludings? | | > is.restrictedBy(...allowedItems) | Is the array only includes allowed items? | | > is.distinct() | Is items of the array are all different? | | Date validator creators | | | > is.moment(date) | Is the date object at the moment of the base date object? | | > is.laterThan(date) | Is the date object later than the base date object? | | > is.atEarliest(date) | Is the date object at earliest the base date object? | | > is.earlierThan(date) | Is the date object earlier than the base date object? | | > is.atLatest(date) | Is the date object at latest the base date object? |

Validator operator reference

Basic

op: so
Will be valid when the validator returns true. It is usually not necessary.

op.so(validator)

Example:

const validate = op.so(is.same('hello'));
validate('hello'); // => true
validate('bye'); // => false

op: not
Will be valid when the validator returns false.

op.not(validator)

Example:

const validate = op.not(is.same('hello'));
validate('bye'); // => true
validate('hello'); // => false

op: and
Will be valid when all validators return true.

op.and(validator1, validator2, ...validators)

Example:

const validate = op.and(is.integer(), is.greaterThan(100));
validate(120); // => true
validate(80); // => false
validate(123.456); // => false

op: or
Will be valid when any validator returns true.

op.or(validator1, validator2, ...validators)

Example:

const validate = op.or(is.nul(), is.integer());
validate(null); // => true
validate(123); // => true
validate('abc'); // => false

op: every
Will be valid when validator returns true on all elements in the array.

op.every(validator)

Example:

const validate = op.every(is.integer());
validate([1, 2, 3]); // => true
validate([1, 2.22, 3]); // => false

op: some
Will be valid when validator returns true on any element in the array.

op.some(validator)

Example:

const validate = op.some(is.integer());
validate([1, 2, 3]); // => true
validate([1.11, 2, 3.33]); // => true
validate([1.11, 2.22, 3.33]); // => false

op: shape
Will be valid when value is an object and all validator returns true on each key.

op.shape({
  [key1]: validator1,
  [key2]: validator2,
  ...keysWithValidator,
})

Example:

const validate = op.shape({
  id: is.integer(),
  name: is.string(),
});
validate({ id: 123, name: 'Mr. Sandman' }); // => true
validate({ id: 123, name: 'Mr. Sandman', active: true }); // => true
validate({ id: 123 }); // => false
validate({ id: 123, name: 456 }); // => false

op: exact
Will be valid when value is an object with specific keys and all validator returns true on each key.

op.exact({
  [key1]: validator1,
  [key2]: validator2,
  ...keysWithValidator,
})

Example:

const validate = op.exact({
  id: is.integer(),
  name: is.string(),
});
validate({ id: 123, name: 'Mr. Sandman' }); // => true
validate({ id: 123, name: 'Mr. Sandman', active: true }); // => false
validate({ id: 123 }); // => false
validate({ id: 123, name: 456 }); // => false

Converter

op: convert
Will be valid when successfully converts the value and the validation is success.

op.convert(converter, validator)

Example:

const validate = op.convert(
  numeric => parseFloat(numeric),
  is.greaterThan(100)
);
validate('150'); // => true
validate('50'); // => false

op: to float
Will be valid when successfully converts to a float and the validation is success.

op.toFloat(validator)

Example:

const validate = op.toFloat(is.greaterThan(1.2));
validate('1.5'); // => true
validate('two'); // => false
validate('0.8'); // => false

op: to integer
Will be valid when successfully converts to an integer and the validation is success.

op.toInteger(validator)

Example:

const validate = op.toInteger(is.greaterThan(100));
validate('150'); // => true
validate('two'); // => false
validate('123.456'); // => false
validate('50'); // => false

op: to length
Will be valid when successfully get the length of an array or string and the validation is success.

op.toLength(validator)

Example:

const validate = op.toLength(is.atLeast(3));
validate(['a', 'b', 'c']); // => true
validate('abc'); // => true
validate(['a', 'b']); // => false
validate('ab'); // => false
validate(3); // => false

op: to split
Will be valid when successfully split to the array and the validation is success.

op.toSplit(separator, validator)

Example:

const validate = op.toSplit(',', op.every(is.startsWith('c')));
validate('candy,cookie,coffee'); // => true
validate('candy,cookie,tea'); // => false
validate(123); // => false

op: to keys
Will be valid when successfully get keys of an object and the validation is success.

op.toKeys(validator)

Example:

const validate = op.toKeys(op.every(is.oneOf('id', 'name')));
validate({ id: 123, name: 'Mario' }); // => true
validate({ id: 123, name: 'Mario', age: 20 }); // => false

op: to values
Will be valid when successfully get values of an object and the validation is success.

op.toValues(validator)

Example:

const validate = op.toValues(op.every(is.integer()));
validate({ people: 64, seats: 80 }); // => true
validate({ people: 640, seats: 'many' }); // => false

Validator creator reference

Basic

is: same
Will be valid when base value and compare value are the same by using the SameValueZero algorithm.

is.same(baseValue)

Example:

const validate = is.same('hello');
validate('hello'); // => true

is: one of
Will be valid when one of base values and compare value are the same by using the SameValueZero algorithm.

is.oneOf(...baseValues)

Example:

const validate = is.oneOf(100, '100', 'one hundred');
validate('100'); // => true

is: defined
Will be valid when the value is defined (not undefined).

is.defined()

Example:

const validate = is.defined();
validate(123); // => true
validate(undefined); // => false

is: not defined
Will be valid when the value is not defined (undefined).

is.notDefined()

Example:

const validate = is.notDefined();
validate(undefined); // => true
validate(123); // => false

is: nul
Will be valid when the value is null.

is.nul()

Example:

const validate = is.nul();
validate(null); // => true
validate(123); // => false

is: nil
Will be valid when the value is undefined or null.

is.nil()

Example:

const validate = is.nil();
validate(undefined); // => true
validate(null); // => true
validate(123); // => false

is: bool
Will be valid when the value is a boolean.

is.bool()

Example:

const validate = is.bool();
validate(false); // => true
validate(123); // => false

is: number
Will be valid when the value is a number.

is.number()

Example:

const validate = is.number();
validate(123); // => true
validate('abc'); // => false

is: string
Will be valid when the value is a string.

is.string()

Example:

const validate = is.string();
validate('abc'); // => true
validate(123); // => false

is: object
Will be valid when the value is a non null object.

is.object()

Example:

const validate = is.object();
validate({ key: 'value' }); // => true
validate({}); // => true
validate(null); // => false
validate(123); // => false

is: func
Will be valid when the value is a function.

is.func()

Example:

const validate = is.func();
validate(() => {}); // => true
validate(123); // => false

is: symbol
Will be valid when the value is a symbol.

is.symbol()

Example:

const validate = is.symbol();
validate(Symbol('abc')); // => true
validate('abc'); // => false

is: instance of
Will be valid when the value is the instance of a constructor.

is.instanceOf(constructor)

Example:

const validate = is.instanceOf(Date);
validate(new Date()); // => true
validate(123); // => false

is: float
Will be valid when the value is a float and not NaN or infinity.

is.float()

Example:

const validate = is.float();
validate(123.456); // => true
validate(123); // => true
validate('123'); // => false

is: integer
Will be valid when the value is a integer and not NaN or infinity.

is.integer()

Example:

const validate = is.integer();
validate(123); // => true
validate(123.456); // => false

is: array
Will be valid when the value is an array object.

is.array()

Example:

const validate = is.array();
validate([1, 2, 3]); // => true

is: date
Will be valid when the value is a valid date object.

is.date()

Example:

const validate = is.date();
validate(new Date()); // => true
validate(new Date('invalid date')); // => false
validate('invalid date'); // => false

Math

is: equal to
Will be valid when the value is equal to the number.

is.equalTo(num)

Example:

const validate = is.equalTo(100);
validate(100); // true
validate(200); // false

is: greater than
Will be valid when the value is greater than the number.

is.greaterThan(num)

Example:

const validate = is.greaterThan(100);
validate(101); // => true
validate(100); // => false

is: at least
Will be valid when the value is at least the number.

is.atLeast(num)

Example:

const validate = is.atLeast(100);
validate(100); // => true
validate(99); // => false

is: less than
Will be valid when the value is less than the number.

is.lessThan(num)

Example:

const validate = is.lessThan(200);
validate(199); // => true
validate(200); // => false

is: at most
Will be valid when the value is at most the number.

is.atMost(num)

Example:

const validate = is.atMost(200);
validate(200); // => true
validate(201); // => false

is: between
Will be valid when the value is between the numbers.

is.between(min, max)

Example:

const validate = is.between(0, 10);
validate(5); // => true
validate(0); // => false
validate(10); // => false

is: from to
Will be valid when the value is from and to the numbers.

is.fromTo(min, max)

Example:

const validate = is.fromTo(1, 9);
validate(1); // => true
validate(9); // => true
validate(0); // => false
validate(10); // => false

Text

is: match
Will be valid when the value matches the regular expression.

is.match(regexp)

Example:

const validate = is.match(/^b[aeiou]t$/);
validate('bat'); // => true
validate('brt'); // => false

is: starts with
Will be valid when the value starts with the wording.

is.startsWith(wording)

Example:

const validate = is.startsWith('net');
validate('network'); // => true
validate('artwork'); // => false

is: ends with
Will be valid when the value ends with the wording.

is.endsWith(wording)

Example:

const validate = is.endsWith('fox');
validate('firefox'); // => true
validate('firewall'); // => false

is: contains
Will be valid when the value contains the wording.

is.contains(wording)

Example:

const validate = is.contains('lie');
validate('believe'); // => true
validate('behave'); // => false

List

is: includes
Will be valid when the array value includes all includings.

is.includes(including1, including2, ...includings)

Example:

const validate = is.includes(10, 20, 30);
validate([0, 10, 20, 30, 40]); // => true
validate([0, 20, 40]); // => false

is: excludes
Will be valid when the array value excludes all excludings.

is.excludes(excluding1, excluding2, ...excludings)

Example:

const validate = is.excludes(5, 15, 25);
validate([0, 10, 20, 30]); // => true
validate([5, 10]); // => false

is: restricted by
Will be valid when the array value is restricted by allowed items.

is.restrictedBy(allowedItem1, allowedItem2, ...allowedItems)

Example:

const validate = is.restrictedBy(5, 10, 15, 20);
validate([10, 20]); // => true
validate([5, 10, 15, 20, 25, 30]); // => false

is: distinct
Will be valid when items of array value are all different.

is.distinct()

Example:

const validate = is.distinct();
validate([1, 2, 3]); // => true
validate([1, 2, 3, 3]]); // => false