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 Validator from '@briza/wegood';
import {
equal,
length,
pattern,
} from '@briza/wegood';
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}$/)
]);
ratingValidator.validate(1);
idValidator.validate('a1234-4', false );
ratingValidator.valid(1);
idValidator.errors('a1234-4');
idValidator.errors('a1234-4');
idValidator.errors('a1234-4', true );
Validator Methods
import Validator from '@briza/wegood';
import { present } from '@briza/wegood';
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
Validate
Validate against the tested value, it returns the Validation Result.
Validation Result
The Validation Result is a object with these properties:
Property | Type | Note | Example |
---|
valid | boolean | Validity state. | true |
errors | string[] | Collection of captured validation errors. | ['this field is required'] |
Example
{
valid: true,
errors: []
}
{
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)
validator.validate(testedValue, false)
Valid
Validity predicate against the tested value.
Code documentation.
validator.valid(testedValue)
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)
validator.errors(testedValue, true)
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)
Argument | Notes | Example |
---|
errorMessage | Error 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
present('error message');
Equal
Verify that the tested value is equal to another.
import { equal } from '@briza/wegood';
Function Arguments
equal(errorMessage, value|customMatcher)
Argument | Notes | Example |
---|
errorMessage | Error message. | 'the value must be 5' |
value | The equal value. | 5 |
customMatcher | Custom equality predicate function. | (value) => value === 5 |
Code documentation.
Example
equal('error message', 5);
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)
Argument | Notes | Example |
---|
errorMessage | Error message. | 'invalid email format' |
pattern | Regular expression used to validate the value. | /^[^@]+@.*\.[a-z]{2, 5}$/ |
Code documentation.
Example
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)
Argument | Notes | Example |
---|
errorMessage | Error message. | 'the value must be in range 3-10' |
min | Minimal boundary. If set to undefined or null , it is being ignored. | 3 |
max | Maximal boundary. If set to undefined or null , it is being ignored. | 10 |
Code documentation.
Example
range('error message', 3, 10);
range('error message', 3);
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)
Argument | Notes | Example |
---|
errorMessage | Error message. | 'the value must be 3-10 characters long' |
min | Minimal length. If set to undefined or null , it is being ignored. | 3 |
max | Maximal length. If set to undefined or null , it is being ignored. | 10 |
Code documentation.
Example
length('error message', 3, 10);
length('error message', 3);
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)
Argument | Notes | Example |
---|
errorMessage | Error message. | 'invalid value' |
exclusions | Array of exclusions. | [1,2,3] |
Code documentation.
Example
exclude('error message', [1, 2, 3]);
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)
Argument | Notes | Example |
---|
errorMessage | Error message. | 'invalid value' |
inclusions | Array of inclusions. | [1,2,3] |
Code documentation.
Example
include('error message', [1, 2, 3]);
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)
Argument | Notes | Example |
---|
errorMessage | Error message. | 'the date in not in valid range.' |
start | Start 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 |
end | End 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 |
transform | Custom 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.
Annotation | Meaning | Example |
---|
0 | Today. | 0 |
-1 | In past. | -1 |
1 | In future. | 1 |
-Nd | N days in past, relative from today. | -10d |
Nd | N days in past, relative from today. | 10d |
-Nw | N weeks in past, relative from today. | -2w |
Nw | N weeks in past, relative from today. | 2w |
-Nm | N months in past, relative from today. | -6m |
Nm | N months in past, relative from today. | 6m |
-Ny | N years in past, relative from today. | -2y |
Ny | N years in past, relative from today. | 2y |
Example
date('error message', '2000-12-30', '2020-06-29');
date('error message', new Date('2000-12-30T00:00:00+00:00'), new Date('2020-06-29T00:00:00+00:00'));
date('error message', '2000-12-30');
date('error message', new Date('2000-12-30T00:00:00+00:00'))
date('error message', undefined|null, '2020-06-29');
date('error message', undefined|null, new Date('2020-06-29T00:00:00+00:00'))
date('error message', -1, 0);
date('error message', 0, 1);
date('error message', '-2y', '3m');
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.
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 {
if (value.match(rx) === null) {
return errorMsg
}
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
- Fork it
- Create your feature branch (git checkout -b ft/new-feature-name)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin ft/new-feature-name)
- 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.