Giter Club home page Giter Club logo

week-validator's Introduction

week-validator

It is easy to use async validator based on ES6 features

How to use

// Init validator instance
let myValidator = new Validator()

// add fields
myValidator.field('name', [
    Validator.filter((str) => String(str)),
    Validator.validator(max, 10).message('Too long name'),
    Validator.validator((str) => new Promise(resolve => setTimeout(() => resolve(true), 1000))),
])

myValidator.array('ages', [
    Validator.validator((item) => _.isNumber(item)),
    Validator.validator((item) => item > 9).message((name) => `${name} is less that 10`),
])

myValidator.field('drinks.alco', [
    Validator.required,
])
myValidator.array('drinks.alco', [
    Validator.validator((item) => _.isObject(item)),
])
myValidator.collection('drinks.alco', 'name', [
    Validator.validator(max, 10).message((name) => `${name} is too long`),
])

// Object to validate
const obj = {
    name: 'hello',
    ages: [10, 25],
    drinks: {
        alco: [
            {
                name: 'Vodka',
            },
            {
                name: 'Beer',
            },
        ],
    },
}

// validate
try {
    await myValidator.validate(obj)
    console.log('Validation Success')
} catch (err) {
    console.error(err.message)
    for (let field of err.fields) {
        console.error(field.errors)
    }
}

 // full varsion in example/example.js

Some explanation

To use validator it is not enough just add functions to array. It has to be prepared. It is easy to create validation or filtration function.

// let any function to validate be
_.isString // from lodash

let myIsString = Validator.validator(_.isString)
let myConvertToString = Validator.filter((str) => String(str))

new Validator()

Initialize a validator object.

myValidator.field(fieldName, validationQueue)

This function applies a field validation queue by field name. For nested field names use dot notation (a.b[0].c).

Can be used once for a filed name.

myValidator.array(fieldName, validationQueue)

This function applies a validation queue for each element of array gotten by field name. For nested field names use dot notation (a.b[0].c).

Can be used once for a filed name.

myValidator.collection(fieldName, subFieldName, validationQueue)

This function applies a validation queue for each element of collection gotten by field name and internam path on object from subFieldName. For nested field names use dot notation (a.b[0].c) on both.

Can be used once for a filed name and sub field name.

Following methods allow you to use any function as a validator or filter in validation queue.

Validator.validator(method, ...opts)

Validator is the function, that accept or decline data validity for an input. For example, if you expect a string with ength 10, but the field contains "abcdefghigk", the function has to return false. If a validation function uses promise, then true or false expects as argument in then() or as a catch.

  • method is the validation function. (sync or async)
  • opts is prepared options.
  • returns { message(text) }

Validator.filter(method, ...opts)

Filter is the function which mutates an input data. For example, you may convert any type to Number or trim a string. If a filter function uses promise, then filter expects a mutated data in then(). Or catch for errors. (for custom errors use Validator.FieldError)

  • method is the filter function. (sync or async)
  • opts is prepared options.
  • returns { message(text) }

Validator.[validator(...)|filter(...)].message(text: String|Function)

Instead of default message of error you able to define your own.

  • name as function takes argument name to be set internally. Ex.: .message((name) => `${name} is wrong!`)

Internal Validators

Validator.required

Check if param is exists in list, make an error if not.

Contribution

Code is far from to be perfect. Feel free to create issues and PRs ;)

week-validator's People

Contributors

seitbekir avatar sseidametov avatar

Watchers

 avatar  avatar  avatar

week-validator's Issues

Create Array/Collection check of top level

Make a check that will be easy to apply for arrays.

Currently we may use collection check and do hack:

// ...
const { collection: form } = validator.validate({ collection: req.body });
// ...

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.