Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@briza/wegood

Package Overview
Dependencies
Maintainers
2
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@briza/wegood

Tiny validation library, so wegood with data.

  • 1.0.6
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
124
decreased by-48.12%
Maintainers
2
Weekly downloads
 
Created
Source

wegood

Tiny validation library, so wegood with data.

Revision: January 29, 2020.

About

This project has been developed to provide a shared validation logic between front-end and back-end code, easily extend-able with custom rules.

  • It is unit tested with 100% code coverage.
  • Easily localized validation messages.
  • Plug & play custom validation rules.
  • Not dependent on any library.
  • Readable and declarative validation rules.

The library is being build as CommonJS module and ESM.

Code documentation could be found here: https://briza-insurance.github.io/wegood/index.html.

Installation via NPM or Yarn

npm install -D @briza/wegood
yarn add @briza/wegood -D

Table of Content



Basic Usage

// Import the Validator.
import Validator from '@briza/wegood';

// Import some of the predefined validation rules.
import {
  equal,
  length,
  pattern,
} from '@briza/wegood';

/**
 * Create a new instances of the validator with given rules.
 */

const ratingValidator = new Validator([
  present('The rating is required.'),
  equal('The value must be 5.', 5)
]);

const idValidator = new Validator([
  present('The ID is required.'),
  length('The value must 9 characters long.', 9, 9),
  pattern('The value must be in A000-0000 format, where 0 could be any number.', /^A\d{3}-\d{4}$/)
]);

/**
 * Use one of the validation methods.
 */

// Return the validation result:
// { valid: boolean, errors: [] }
// Errors contains the error message of the first not-satisfied rule.
ratingValidator.validate(1);

// Return the validation result:
// { valid: boolean, errors: [] }
// Errors contains the error message of all not-satisfied rules.
idValidator.validate('a1234-4', false /* firstErrorOnly */);

// Return true if valid, false otherwise.
ratingValidator.valid(1);

// Return array of error messages of all not-satisfied rules.
idValidator.errors('a1234-4');

// Return array of error messages of all not-satisfied rules.
idValidator.errors('a1234-4');

// Return only the first error message of the not-satisfied rule, still returned as an array.
idValidator.errors('a1234-4', true /* firstErrorOnly */);

Validator Methods

// Import the Validator.
import Validator from '@briza/wegood';
import { present } from '@briza/wegood';

// Create the validator.
const validator = new Validator([present('this field is required.')]);

There is collection of functions to provide implementation agnostic approach:

Rules

Get the validator rules.

Code documentation.

validator.rules
// validation rules (function[])
Validate

Validate against the tested value, it returns the Validation Result.

Validation Result

The Validation Result is a object with these properties:

PropertyTypeNoteExample
validbooleanValidity state.true
errorsstring[]Collection of captured validation errors.['this field is required']

Example

// Valid
{
  valid: true,
  errors: []
}

// Invalid
{
  valid: false,
  errors: ['invalid email format']
}

Passing false as the seconds parameter, returns collection of all validation errors, if any.

Code documentation.

validator.validate(testedValue)
/**
 * {
 *  valid: true|false,
 *  errors: []
 * }
 * 
 * The errors will contain only first discovered error.
 * 
 */

validator.validate(testedValue, false)
/**
 * {
 *  valid: true|false,
 *  errors: []
 * }
 * 
 * The errors will contain all discovered error.
 * 
 */
Valid

Validity predicate against the tested value.

Code documentation.

validator.valid(testedValue)
// true | false
Errors

Get the validation errors. if any.

Code documentation.

Passing true as the seconds parameter, returns only the first validation error, if any.

validator.errors(testedValue)
// string[]
// All errors will be captured.

validator.errors(testedValue, true)
// string[]
// Only the first error will be captured.

Builtin Validation Rules

All builtin validation rules have this construct:

function rule(errorMessage: string, agr1: any, ... argN: any): (value: any) => true|string
  • A function which returns the validation rule function with set error message, plug-able into the Validator, or it could be used individually, e.g. rule('error message')(testValue).
  • The args differs form rule to rule.
  • Please see Custom Validation Rule for more information.

Present

Verify that the tested value is present, i.e. defined and not empty.

import { present } from '@briza/wegood';

Function Arguments

present(errorMessage)
ArgumentNotesExample
errorMessageError message.'the value must be 5'

Code documentation.

  • Non-empty array tested value is evaluated as valid.
  • Empty string tested value is evaluated as invalid.
  • Object, Function tested value throws an error.

Example

// The value must have some value.
present('error message');

Equal

Verify that the tested value is equal to another.

import { equal } from '@briza/wegood';

Function Arguments

equal(errorMessage, value|customMatcher)
ArgumentNotesExample
errorMessageError message.'the value must be 5'
valueThe equal value.5
customMatcherCustom equality predicate function.(value) => value === 5

Code documentation.

Example

// The value must be equal to 5.
equal('error message', 5);

// Custom matcher.
equal('error message', (value) => {
  return value === 5;
});

Pattern

Verify that the tested value is matches the pattern.

import { pattern } from '@briza/wegood';

Function Arguments

pattern(errorMessage, pattern)
ArgumentNotesExample
errorMessageError message.'invalid email format'
patternRegular expression used to validate the value./^[^@]+@.*\.[a-z]{2, 5}$/

Code documentation.

Example

// The value must match the given pattern.
pattern('error message', /^[^@]+@.*\.[a-z]{2, 5}$/);

Range

Verify that the tested value is in the given range (inclusive).

  • Applicable only on the number values, although the rule auto-converts string into number if it is a valid number.
  • Could be also used as MAX and MIN.
import { range } from '@briza/wegood';

Function Arguments

range(errorMessage, min, max)
ArgumentNotesExample
errorMessageError message.'the value must be in range 3-10'
minMinimal boundary. If set to undefined or null, it is being ignored.3
maxMaximal boundary. If set to undefined or null, it is being ignored.10

Code documentation.

Example

// The value must be between 3 and 10.
range('error message', 3, 10);

// The value must be 3 and above, aka MIN.
range('error message', 3);

// The value must be 10 and bellow, aka MAX.
range('error message', null|undefined, 10);

Length

Verify that the tested value is in the given string length range (inclusive).

  • Applicable only on the string values, although the rule auto-converts numbers into strings.
  • Could be also used as MAX and MIN.
import { length } from '@briza/wegood';

Function Arguments

length(errorMessage, min, max)
ArgumentNotesExample
errorMessageError message.'the value must be 3-10 characters long'
minMinimal length. If set to undefined or null, it is being ignored.3
maxMaximal length. If set to undefined or null, it is being ignored.10

Code documentation.

Example

// The value must be 3 up to 10 characters long.
length('error message', 3, 10);

// The value must be 3 and more characters long, aka MIN.
length('error message', 3);

// The value must be 10 and less characters long, aka MAX.
length('error message', null|undefined, 10);

Exclude

Verify that the tested value is not the exclusion list.

import { exclude } from '@briza/wegood';

Function Arguments

exclude(errorMessage, exclusions)
ArgumentNotesExample
errorMessageError message.'invalid value'
exclusionsArray of exclusions.[1,2,3]

Code documentation.

Example

// The value must not be contained in the list.
exclude('error message', [1, 2, 3]);

// The value must not be contained in the list.
exclude('error message', ['circle', 'square', 'triable']);

Include

Verify that the tested value is not the exclusion list.

import { include } from '@briza/wegood';

Function Arguments

include(errorMessage, inclusions)
ArgumentNotesExample
errorMessageError message.'invalid value'
inclusionsArray of inclusions.[1,2,3]

Code documentation.

Example

// The value must be contained in the list.
include('error message', [1, 2, 3]);

// The value must be contained in the list.
include('error message', ['circle', 'square', 'triable']);

Date

Verify that the tested value is the date range.

import { date } from '@briza/wegood';

Function Arguments

date(errorMessage, start, end, transform)
ArgumentNotesExample
errorMessageError message.'the date in not in valid range.'
startStart date boundary - ISO date string (yyyy-mm-dd), Date object, or Relative Date Offset. If set to undefined or null, it is being ignored.3
endEnd date boundary - ISO date string (yyyy-mm-dd), Date object, or Relative Date Offset. If set to undefined or null, it is being ignored.3
transformCustom Date object transformer function. Optional.(value) => new Date(value)

Code documentation.

Relative Date Offset

Instead of a concrete ISO date string or Date object below annotated shortcodes might be used to set the date boundary relative to TODAY date.

AnnotationMeaningExample
0Today.0
-1In past.-1
1In future.1
-NdN days in past, relative from today.-10d
NdN days in past, relative from today.10d
-NwN weeks in past, relative from today.-2w
NwN weeks in past, relative from today.2w
-NmN months in past, relative from today.-6m
NmN months in past, relative from today.6m
-NyN years in past, relative from today.-2y
NyN years in past, relative from today.2y

Example

/**
 * The value (date) must between the given data range.
 */
// ISO strings
date('error message', '2000-12-30', '2020-06-29');
// Date objects
date('error message', new Date('2000-12-30T00:00:00+00:00'), new Date('2020-06-29T00:00:00+00:00'));

/**
 * The value (date) must after the date.
 */
// ISO string
date('error message', '2000-12-30');
// Date object
date('error message', new Date('2000-12-30T00:00:00+00:00'))

/**
 * The value (date) must before the date.
 */
// ISO string
date('error message', undefined|null, '2020-06-29');
// Date object
date('error message', undefined|null, new Date('2020-06-29T00:00:00+00:00'))

/**
 * Relative offsets, relative to today.
 */

// Any date in past, until today.
date('error message', -1, 0);

// Any date in future, starts from today.
date('error message', 0, 1);

// Any date between 2 years ago, up to 3 months from today.
date('error message', '-2y', '3m');

// Combined fixed date with relative date.
// Any date from 2000-12-30 until today.
date('error message', '2000-12-30', 0);

Date Tested Value Format

The tested value must be passed to the validation rule in the ISO date string (yyyy-mm-dd) or as a Date object, otherwise the validation rule throws an error. The transform function could be passed to the rule to handle custom conversion from mixed value into the Date object.

// Custom transform function
date('error message', '2000-12-30', '2020-06-29', (value) => new Date(value));

Custom Validation Rule

Validation rule blueprint (typescript):

function email(errorMsg: string): ValidationRule {
  const rx = /^[^@]+@.*\.[a-z]{2,5}$/
  return (value: any): true|string {
    // Invalid value
    if (value.match(rx) === null) {
      return errorMsg
    }
    // Valid value
    return true
  }
}

  • ValidationRule (typescript type), represents: (value) => true|string, where:
    • true = valid.
    • string = error message.

Contributing

When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.

Pull Request Process

  1. Fork it
  2. Create your feature branch (git checkout -b ft/new-feature-name)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin ft/new-feature-name)
  5. Create new Pull Request

Please make an issue first if the change is likely to increase.

License

wegood is released under the MIT license. See LICENSE.txt.

Keywords

FAQs

Package last updated on 14 Feb 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc