GithubHelp home page GithubHelp logo

vlad-rz / js-validator-livr Goto Github PK

View Code? Open in Web Editor NEW

This project forked from koorchik/js-validator-livr

0.0 2.0 0.0 371 KB

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

License: MIT License

JavaScript 100.00%

js-validator-livr's Introduction

LIVR Validator

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

npm version Build Status Known Vulnerabilities

SYNOPSIS

Common usage:

const LIVR = require('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());
}

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'
        }
    }
}});

DESCRIPTION

See LIVR Specification 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)

JavaScript version extra features:

  • Zero dependencies
  • Works in NodeJs and in a browser
  • 3.6kb (min+gzip), 13kb (minified)
  • You can find more rules in livr-extra-rules

INSTALL

nodejs/npm

npm install livr

Browser (if you do not use npm)

You can find prebuilt browser versions in "dist" folder (livr-debug.js - not minified development version with source maps, livr-min.js - minified production version). Possible you will need some polyfills ("isInteger" etc) for older browsers.

CLASS METHODS

new LIVR.Validator(livr, isAutoTrim);

Constructor creates validator objects. livr - validations rules. Rules description is available here - https://github.com/koorchik/LIVR

isAutoTrim - asks validator to trim all values before validation. Output will be also trimmed. if isAutoTrim is undefined(or null) than 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.

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

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

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.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();
}

validator.getErrors()

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.

AUTHOR

koorchik (Viktor Turskyi)

BUGS

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

js-validator-livr's People

Contributors

danielhreben avatar koorchik avatar pterolex avatar reiz avatar spaintrain avatar striped-s0cks avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.