2.0.0 • Published 5 years ago

basic-validator v2.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

basic-validator

Installation

yarn add basic-validator or npm install basic-validator

Usage

Import

Import or require Validator to be consumed:

import { Validator } from 'basic-validator';

Create Validator

Once imported, instantiate with:

const password = new Validator();

Validator methods

methodargumentdescription
rule()Object {}Add a validation rule
validate()Value to be validatedLoop over all validation rules, returning an object containing valid (boolean) and errors (array)

Adding rules with .rule({...obj})

To add a rule to a validator, call rule({}) on the Validator instance, passing the following object {}:

paramrequiredtypedescription
fnyesFunctionFunction to be called when validating
messageyesStringMessage to be added to errors array upon failure
paramsnoArrayParameters (in order) to be passed to function
⭐ Rule expectations
  • The function (fn) passed to the rule must return true or false. These can be custom validation functions or imported from many of the validation libraries.
  • The function (fn) must accept the testing value as its first parameter.
  • If parameters (params) are passed to the rule, they must be in order as per the functions documentation.

Example usage:

password.rule({
  fn: containsSpecialChar,
  message: 'Must contain special character'
});
password.rule({
  fn: charsBetween,
  message: 'Characters must be between 10 and 15',
  params: [10, 15]
});

Rules can also be chained:

password
  .rule({
    fn: charsBetween,
    params: [10, 15],
    message: 'Chars need to be between 10 and 15'
  })
  .rule({
    fn: containsUnderscore,
    message: 'Must contain an underscore'
  })
  .rule({
    fn: containsDash,
    message: 'Must contain a dash'
  });

Validating with .validate(val)

Once the Validator has been created and rules added, running validation can be called with .validate(val) - passing the value to be validated. The validate function will return an object containing two keys; valid and errors.

The key valid will be a boolean, errors will be an array of messages defined from the rules.

For example:

password.validate('hello');
// {
//   valid: false,
//   errors: ['Must contain an underscore', 'Must contain a dash']
// }
password.validate('pass-word_here');
// {
//   valid: true,
//   errors: []
// }