@zipavlin/niggle

1.0.5 • Public • Published

Niggle

Niggle is a tiny, customizable javascript value validator with laravel inspired syntax and no dependencies.

installation

Install using npm install @zipavlin/niggle

example

    const niggle = require('@zipavlin/niggle');
    const validate = new Niggle({
        // optional options
        messages: {
            min: 'Your input is too low! Is should be higher than {{options}}'
        }
    }).validate;
    console.log(validate('min:2|max:5', 3));

methods

Validator has only few public methods:

  1. validate(String validator, String|Int input) - validate input agains validator string and return validity and errors: {valid: Bool, errors: Array|null }
  2. valid(String validator, String|Int input) - validate input agains validator string and return validity: Bool
  3. errors(String validator, String|Int input) - validate input agains validator string and return array of errors: Array|null
  4. registerValidators(Array validators) - register validators
  5. registerPlugins(Array plugins)

validators

core

Name Options Example Description
min Number 'min:5' length (of string) or amount (for number) must be higher than option
max Number 'max:5' length (of string) or amount (for number) must be lower than option
between Number,Number 'between:1,5' length (of string) or amount (for number) must be between first option and second option
length Number 'length:5' length (of string) or amount (for number) must be equal to option
email Null 'email' input must match email pattern
is Number/String 'is:"must be this"' input must be equal to option (type included)
pattern Pattern 'pattern:^\d{2}$' input must match pattern

creating and adding validators

Validator is basically an object with required name, message and callback properties:

const customValidator = {
    name: 'min_or_equal', // required - is used as validator key.
    synonym: 'gte', // optional
    type: 'number', // optional - is passed to callback. Can be: string, number, range, array
    message: 'Input must be higher or equal to {{options}}', // required -- default error message with value injection. Possible dynamic values include options (including arrays), type, input
    callback: (input, options, type) => { // required
        return isNaN(input) ? (input.length >= options) : (input >= options);
    }
}
const validator = new Validator();
validator.registerValidators(customValidator);
validator.validate('min_or_equal:19', 'this is test string'); // true

plugins

Plugins are not supported in this moment, but are planned.

Package Sidebar

Install

npm i @zipavlin/niggle

Weekly Downloads

1

Version

1.0.5

License

MIT

Unpacked Size

15.1 kB

Total Files

5

Last publish

Collaborators

  • zipavlin