• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 12 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Lightweight javascript validator supporting Language Independent Validation Rules Specification (LIVR)

LIVR Validator

LIVR.Validator - Lightweight JavaScript validator supporting Language Independent Validation Rules Specification (LIVR).

npm version Known Vulnerabilities

SYNOPSIS

There are 2 implementations:

  1. "Validator" supports only synchronous rules. All built-in rules are synchronous.
  2. "AsyncValidator" (experimental) supports both synchronous and asynchronous rules.

Common usage:

import LIVR from 'livr';
LIVR.Validator.defaultAutoTrim(true);

const validator = new LIVR.Validator({
    name: 'required',
    email: ['required', 'email'],
    gender: { one_of: ['male', 'female'] },
    phone: { max_length: 10 },
    password: ['required', { min_length: 10 }],
    password2: { equal_to_field: 'password' },
});

const validData = validator.validate(userData);

if (validData) {
    saveUser(validData);
} else {
    console.log('errors', validator.getErrors());
}

All standard rules are supported in camel case as well (Validator.registerDefaultRules always does autocamelization):

Camel case names are closer to JS naming conventions but underscore rule names are more compatible with LIVR spec.

import LIVR from 'livr';
LIVR.Validator.defaultAutoTrim(true);

const validator = new LIVR.Validator({
    name: 'required',
    email: ['required', 'email'],
    gender: { oneOf: ['male', 'female'] },
    phone: { maxLength: 10 },
    password: ['required', { minLength: 10 }],
    password2: { equalToField: 'password' },
});

const validData = validator.validate(userData);

if (validData) {
    saveUser(validData);
} else {
    console.log('errors', validator.getErrors());
}

Common usage of async version:

import LIVR from 'livr/async';
LIVR.AsyncValidator.defaultAutoTrim(true);

const validator = new LIVR.AsyncValidator({
    name: 'required',
    email: ['required', 'email'],
    gender: { one_of: ['male', 'female'] },
    phone: { max_length: 10 },
    password: ['required', { min_length: 10 }],
    password2: { equal_to_field: 'password' },
});

try {
    const validData = await validator.validate(userData);
    saveUser(validData);
} catch (errors) {
    console.log('errors', errors);
}

You can use modifiers separately or can combine them with validation:

const validator = new LIVR.Validator({
    email: ['required', 'trim', 'email', 'to_lc'],
});

Feel free to register your own rules:

You can use aliases(preferable, syntax covered by the specification) for a lot of cases:

const validator = new LIVR.Validator({
    password: ['required', 'strong_password'],
});

validator.registerAliasedRule({
    name: 'strong_password',
    rules: { min_length: 6 },
    error: 'WEAK_PASSWORD',
});

Or you can write more sophisticated rules directly:

const validator = new LIVR.Validator({
    password: ['required', 'strong_password'],
});

validator.registerRules({
    strong_password() {
        return (value) => {
            // We already have "required" rule to check that the value is present
            if (value === undefined || value === null || value === '') return;

            if (value.length < 6) {
                return 'WEAK_PASSWORD';
            }
        };
    },
});

Or you can write more sophisticated async rules as well:

const validator = new LIVR.AsyncValidator({
    userId: ['required', 'valid_user_id'],
});

validator.registerRules({
    valid_user_id() {
        return async (value) => {
            // We already have "required" rule to check that the value is present
            if (value === undefined || value === null || value === '') return;

            const user = await Users.findUserById(value);

            if (!user) {
                return 'WRONG_USER_ID';
            }
        };
    },
});

If you use LIVR in browser, you can import only the rules you use (it can reduce budle size a little bit):

import Validator from 'livr/lib/Validator';

Validator.registerDefaultRules({
    required: require('livr/lib/rules/common/required'),
    email: require('livr/lib/rules/special/email'),
    one_of: require('livr/lib/rules/string/one_of'),
    min_length: require('livr/lib/rules/string/min_length'),
    max_length: require('livr/lib/rules/string/max_length'),
    equal_to_field: require('livr/lib/rules/special/equal_to_field'),
});

Validator.defaultAutoTrim(true);

// Anywhere in your app
import Validator from 'livr/lib/Validator';

const validator = new Validator({
    name: 'required',
    email: ['required', 'email'],
    gender: { one_of: ['male', 'female'] },
    phone: { max_length: 10 },
    password: ['required', { min_length: 10 }],
    password2: { equal_to_field: 'password' },
});

const validData = validator.validate(userData);

if (validData) {
    saveUser(validData);
} else {
    console.log('errors', validator.getErrors());
}

DESCRIPTION

See LIVR Specification and rules documentation for detailed documentation and list of supported rules.

Features:

  • Rules are declarative and language independent
  • Any number of rules for each field
  • Return together errors for all fields
  • Excludes all fields that do not have validation rules described
  • Has possibility to validate complex hierarchical structures
  • Easy to describe and understand rules
  • Returns understandable error codes(not error messages)
  • Easy to add own rules
  • Rules are be able to change results output ("trim", "nested_object", for example)
  • Multipurpose (user input validation, configs validation, contracts programming etc)
  • Supports sync and async validation

JavaScript version extra features:

  • Zero dependencies
  • Works in NodeJs and in a browser
  • Validator (without rules) less than 1KB (min+gzip)
  • Validator with all rules 2.84KB (min+gzip)
  • You can find more rules in livr-extra-rules

ASYNC VALIDATION (NEW)

LIVR supports async validation but it was added only in v2.5. So, it uses a little bit different API.

What you need to know about implementation:

  1. All simple sync rules are supported out of the box.
  2. Meta rules (rules that construct a new validator instance inside them) were rewritten to use AsyncValidator. If you import "livr/async" they will be automatically used
  3. Fields validation is done in parallel but rules for one field are processed one after another.

Usage example:

import LIVR from 'livr/async';
LIVR.AsyncValidator.defaultAutoTrim(true);

const validator = new LIVR.AsyncValidator({
    name: 'required',
    email: ['required', 'email'],
});

try {
    const validData = await validator.validate(userData);
    saveUser(validData);
} catch (errors) {
    console.log('errors', errors);
}

INSTALL

nodejs/npm

npm install livr

Browser (if you do not use npm)

You can find prebuilt browser versions in "dist" folder

  • development/main.js - not minified development version with source maps
  • production/main.js - minified production version. Possible you will need some polyfills ("isInteger" etc) for older browsers.
  • development-async/main.js - not minified development version with source maps of "AsyncValidator"
  • production-async/main.js - minified production version of "AsyncValidator"

CLASS METHODS

new LIVR.Validator(rules, options);

Constructor creates validator objects. rules - validations rules. Rules description is available here - https://livr-spec.org/

Supported options:

  • "autoTrim" (default false) - asks validator to trim all values before validation. Output will be also trimmed. If key is not passed then defaultAutoTrim value will be used.

Instead of "options" object "isAutoTrim" boolean value can be passed for compatibility with previous API. if isAutoTrim is undefined(or null) then defaultAutoTrim value will be used.

LIVR.Validator.registerAliasedDefaultRule(alias)

alias - is a plain javascript object that contains: name, rules, error (optional).

LIVR.Validator.registerAliasedDefaultRule({
    name: 'valid_address',
    rules: {
        nested_object: {
            country: 'required',
            city: 'required',
            zip: 'positive_integer',
        },
    },
});

Then you can use "valid_address" for validation:

{
    address: 'valid_address';
}

You can register aliases with own errors:

LIVR.Validator.registerAliasedDefaultRule({
    name: 'adult_age'
    rules: [ 'positive_integer', { min_number: 18 } ],
    error: 'WRONG_AGE'
});

All rules/aliases for the validator are equal. The validator does not distinguish "required", "list_of_different_objects" and "trim" rules. So, you can extend validator with any rules/alias you like.

Note: Each rule which contains uderscore in name will be additionally registered using camel case name if there is no such rule name already.

LIVR.Validator.registerDefaultRules({"rule_name": ruleBuilder })

ruleBuilder - is a function reference which will be called for building single rule validator.

Note: Each rule which contains uderscore in name will be additionally registered using camel case name if there is no such rule name already.

LIVR.Validator.registerDefaultRules({
    my_rule(arg1, arg2, arg3, ruleBuilders) {
        // ruleBuilders - are rules from original validator
        // to allow you create new validator with all supported rules
        // const validator = new LIVR.Validator(livr).registerRules(ruleBuilders).prepare();

        return (value, allValues, outputArr) => {
            if (notValid) {
                return 'SOME_ERROR_CODE';
            } else {
            }
        };
    },
});

Then you can use "my_rule" for validation:

{
    name1: 'my_rule' // Call without parameters
    name2: { 'my_rule': arg1 } // Call with one parameter.
    name3: { 'my_rule': [arg1] } // Call with one parameter.
    name4: { 'my_rule': [ arg1, arg2, arg3 ] } // Call with many parameters.
}

Here is "max_number" implemenation:

function maxNumber(maxNumber) {
    return (value) => {
        // We do not validate empty fields. We have "required" rule for this purpose
        if (value === undefined || value === null || value === '') return;

        // return error message
        if (value > maxNumber) return 'TOO_HIGH';
    };
}
LIVR.Validator.registerDefaultRules({ max_number: maxNumber });

All rules for the validator are equal. The validator does not distinguish "required", "list_of_different_objects" and "trim" rules. So, you can extend validator with any rules you like.

LIVR.Validator.getDefaultRules();

returns object containing all default ruleBuilders for the validator. You can register new rule or update existing one with "registerRules" method.

LIVR.Validator.defaultAutoTrim(isAutoTrim)

Enables or disables automatic trim for input data. If is on then every new validator instance will have auto trim option enabled

LIVR.util

List of useful utils for writing your rules (see source code)

OBJECT METHODS

validator.prepare()

Parses all validation rules to make subsequent calls faster. This step is always automatically called on first call of validator.validate(input) but you can call it manually if you want to warm up your validator object before validation was called. Usually, it is useful in several cases:

  • Benchmarks. As first validation call will take more time without prepare
  • Custom meta rules. Just to prepare nested validators when parent validator prepare method is called.

validator.validate(input)

Validates user input. On success returns validData (contains only data that has described validation rules). On error return false.

const validData = validator.validate(input);

if (validData) {
    // use validData
} else {
    const errors = validator.getErrors();
}

for AsyncValidator

try {
    const validData = await validator.validate(input);
    // use validData
} catch (errors) {
    // handle errors
}

validator.getErrors() (only for sync version of validator)

Returns errors object.

{
    "field1": "ERROR_CODE",
    "field2": "ERROR_CODE",
    ...
}

For example:

{
    "country":  "NOT_ALLOWED_VALUE",
    "zip":      "NOT_POSITIVE_INTEGER",
    "street":   "REQUIRED",
    "building": "NOT_POSITIVE_INTEGER"
}

validator.registerRules({"rule_name": ruleBuilder})

ruleBuilder - is a function reference which will be called for building single rule validator.

See "LIVR.Validator.registerDefaultRules" for rules examples.

validator.registerAliasedRule(alias)

alias - is a composite validation rule.

See "LIVR.Validator.registerAliasedDefaultRule" for rules examples.

validator.getRules()

returns object containing all ruleBuilders for the validator. You can register new rule or update existing one with "registerRules" method.

Performance

LIVR is fast but you should be aware about following:

Do not construct Validator for each validation call. Construct object once for each schema and reuse validators with different inputs. "validator.validate(input)" is very fast.

In some cases you need to construct object each time, it is slower but still ok. It still will be twice faster than "Joi". LIVR validator preparation (rules compile step) is 100 time faster than "fastest-validator" compile time.

AUTHOR

koorchik (Viktor Turskyi)

Contributors

eNdiD

BUGS

Please report any bugs or feature requests to Github https://github.com/koorchik/js-validator-livr

More Repositories

1

LIVR

Language Independent Validation Rules Specification
Less
287
star
2

node-mole-rpc

Transport agnostic spec compliant JSON RPC client and server
JavaScript
63
star
3

node-confme

Opinionated config library that allows you to have complex config and behaves according to 12-factors apps rules
JavaScript
39
star
4

FastNotes-Proto

Trying mojolicious
JavaScript
32
star
5

jabascript-materials

Materials for my YouTube channel
JavaScript
30
star
6

node-chista

Chista - NodeJs toolkit for building express services with clean architecture
JavaScript
29
star
7

my-talks

List of talks performed by me
20
star
8

react360-virtual-tour

React360 virtual tour created for OdessaJS conference talk
JavaScript
16
star
9

Mojolicious-Plugin-RenderFile

"render_file" helper for Mojolicious to render static files
Perl
16
star
10

js-livr-extra-rules

More validation rules for LIVR (https://www.npmjs.com/package/livr)
JavaScript
15
star
11

node-mystem3

NodeJS wrapper for the Yandex MyStem 3
JavaScript
14
star
12

Validator-LIVR

Lightweight Perl validator supporting Language Independent Validation Rules Specification (LIVR)
Perl
13
star
13

node-semgrex

NodeJs wrapper for Stanford NLP Semgrex
JavaScript
10
star
14

node-hadoop-streaming-utils

Hadoop streaming utils for NodeJS
JavaScript
9
star
15

awesome-software-engineering

List of articles that make you a better software engineer
8
star
16

Mojolicious-Plugin-CSRFProtect

Complete protection from CSRF attacks in Mojolicious application
Perl
8
star
17

perl6-livr

Lightweight Perl6 validator supporting Language Independent Validation Rules Specification (LIVR)
Perl 6
7
star
18

formula-evaluation-benchmark

Benchmark math formula (AST) evaluation in different languages
JavaScript
5
star
19

Mojolicious-Plugin-ValidateTiny

Mojolicious wrapper for Validate::Tiny
Perl
4
star
20

node-mole-rpc-transport-ws

WebSocket(ws) transport for Mole-RPC (JSON RPC library)
JavaScript
4
star
21

Mojolicious-Plugin-JSUrlFor

Mojolicious "url_for" helper for javascript
Perl
4
star
22

workshop-effective-nodejs-development

workshop-effective-nodejs-development
JavaScript
4
star
23

Mojolicious-Plugin-UserManager

( PRE ALPHA PROTOTYPE ) Easy to use user manager for Mojolicious
Perl
4
star
24

codegolf-telegram-bot

Code Golf Telegram Bot (can be used with any programming language)
Perl 6
3
star
25

jsonapi-for-terrans

JSON API for Terrans (PROPOSAL)
3
star
26

scrum-cards-generator

Generate printable scrum cards from Redmine issues
JavaScript
3
star
27

Mojolicious-Plugin-Gravatar

Globally Recognized Avatars for Mojolicious
Perl
3
star
28

node-collections-syncer

PoC: Storage agnostic and simple way to denormalize data for reporting etc (CQRS)
JavaScript
2
star
29

Mojolicious-Plugin-HTMLLint

HTML Lint for Mojolicious
Perl
2
star
30

Hash-Storage

( PRE ALPHA PROTOTYPE ) Multipurpose Persistent Hash Storage
Perl
2
star
31

Mojolicious-Plugin-RemoteAddr

Mojolicious helper for getting remote ip address
Perl
2
star
32

node-mole-rpc-transport-mqtt

MQTT transport for Mole-RPC (JSON RPC library)
JavaScript
2
star
33

node-mole-rpc-transport-webworker

Easy way to communicate with webworker using Mole-RPC (JSON RPC library)
JavaScript
2
star
34

Mojolicious-Plugin-MultiMarkdownRenderer

Markdown and MultiMarkdown templates for Mojolicious
Perl
2
star
35

Query-Abstract

Create filters in Perlish way and transform them into coderefs or SQL
Perl
1
star
36

mysql-commander

ncurses mysql client (OBSOLETE)
Perl
1
star
37

node-hadoop-boilerplate

Boilerplate for Hadoop tasks written in JavaScript
JavaScript
1
star
38

vulnerable-twitter-be

JavaScript
1
star
39

Lingua-UK-Numbers

Converts numbers to money sum in words (in Ukrainian hryvnas)
Perl
1
star
40

Mojolicious-Plugin-BindSessionToIP

Binds your Mojolicious session to IP-address for better security of your application
Perl
1
star
41

js-routes-dispatcher

JS Routes Dispatcher
JavaScript
1
star
42

node-semgrex-demo

Small demo of using Semgrex
JavaScript
1
star
43

Statistics-OnlineCounter

Count interval statistics in realtime
Perl
1
star
44

Debug-LTrace

Perl extension to locally trace subroutine calls
Perl
1
star
45

Mojolicious-Plugin-ChromeLogger

Mojolicious logs in Google Chrome console
Perl
1
star
46

DLM-Client

Linux DLM(Distributed Lock Manager) Client
C
1
star
47

node-import-vs-require

Handling cyclic dependencies with import and require
JavaScript
1
star
48

gatsby-starter-netlify-cms

JavaScript
1
star
49

node-mole-rpc-transport-eventemitter

Event Emitter Mole RPC (JSON RPC library) transport
JavaScript
1
star