maanyakaran

1.2.0 • Public • Published

Maanyakaran Tests

Maanyakarn (मान्यकरण) is a hindi word which means validation, which is the basic offering of this micro framework. Maanyakarn provides easy and extensible way of performing validations over JS objects (primarily states of react, redux and similar frameworks).

Installation

Install the library

 npm install maanyakaran

Usage Guide

Without ES6
var Maanyakaran = require('maanyakaran');
ES6
import Maanyakaran from 'maanyakaran';
Simple example with supplied strategies
var Maanyakaran = require('maanyakaran');
Maanyakaran.addValidationStrategy(Maanyakaran.Strategies.Form);
const constraints = {
    person: {
        name: "Form:nonEmptyString",
        email: "Form:nonEmptyString, Form:validEmail"
    }
}; //contraints should follow json order of the your input

const validationResults  = validator.validate({
    person:
        {
            name: "peter",
            email: "",
            age: 101
        }
});
Concepts
  1. Constraints:
    Maanyakaran class takes constraints object as an argument to its constructor which contains key value pairs, where value defines rules for the key.

        const constraints = {
            anotherName: "nonEmptyString"
        }
        const validator = new Maanyakaran(constraints)
  2. Input:
    Instance of Maanyakaran object invokes validate method with input as an argument and validates input against given constraints.

      validator.validate({anotherName: "maanyakaran"})
  3. validate()
    validate method of Maanyakaran object returns ValidationResults object with keys as per input object and value as an array of error message(s) if the value for the corresponding key is invalid as per the constraints.

    const constraints = {
        person: {
            name: "nonEmptyString",
            email: "nonEmptyString, validEmail"
        }
    }
    const validator = new Maanyakaran(constraints);
    validator.validate({
       person: {
          name: "peter",
          email: ""
       }
    })     
    //    validate returns below output:
    //    {
    //    person: {
    //        email: ["Empty String", "Invalid email"]
    //    }
    //    }
  4. Types of values in constraint
    i. string:
    String could be comma separated strings or just one string.
    Each string could be in the form :
    <Namespace:><validationFunctionName>
    or
    <Namespace:><validationFunctionName-><closureArgument>
    where Namespace is optional, which refers to the name of the library of validators.
    validationFunction is required and it is the function name which is used to validate input.

    eg:

       const constraints = 
         {
             person: {
                 age: "NumberStrategy:lessThan-100",//closure function with 100 as argument
                 name: "nonEmptyString",
                 email: "nonEmptyString, validEmail",
                 count: "NumberStrategy:lessThan100"
             }
         }

    ii. Object:
    value can itself be an object to validate for nested object structure in the input.

    iii. Array object:
    value can also be an array to indicate that the corresponding key can occur multiple times and should be validated as per the containing constraint object in the array.

    eg:

    const constraints = {
        person: {
            children: [
                {
                    name: "nonEmptyString",
                    age: "positiveInteger"
                }
            ]
        }                  
    };
    let expected = validator.validate({
        person: {
            children: [
                {
                    name: "peter",
                    age: -1
                },
                {
                    name: "",
                    age: 5
                }
            ]
        }
    })
    //    expected object 
    //    person: {
    //          children: {
    //             0: {
    //                     age: ["non positive integer"]
    //                 },
    //             1: {
    //                     name: ["Empty String"]
    //                 }
    //             }
    //          }
    //      }

Out of box validation

Maanyakaran comes up with a few built-in validator functions:

| Validator       |                     Description                            |
|-----------------|------------------------------------------------------------|
| nonEmptyString  |    checks if the subject string has a length of zero.      |
| validEmail      |    checks if the subject string is an email.               |
| positiveInteger |    checks if the subject integer is a positive integer.    |

Out of box Strategies

Maanyakaran comes up with a built-in NumberStrategy to validate numbers. It includes following validator functions:

| Validator       | Description                                                                   |
|-----------------|-------------------------------------------------------------------------------|
| positiveInteger | checks if the subject integer is a positive integer.                          |
| lessThan100     | checks if the subject integer is less than 100.                               |
| lessThan        | closure function which takes an argument say k and checks if subject          |
|                 |input is less than k.                                                          |

Creating Custom Strategy or Validations rules

Maanyakaran lets you easily create your own validators that fits your needs. You can register them using addValidationStrategy or addValidationRule.

Validation rule.

One can write it's own custom validation rule for their specific purpose. A validation rule is a simple JS function which is provided with the specific state variable as subject and expect either null in case is given subject passes validation or an error string if it fails validation as output. Refer example below.

addValidationRule

It lets you add a custom validator function.

    Maanyakaran.addValidationRule('greaterThanFive', (subject) => {
        if (subject > 5) {
            return null
        }
        return "Number should be greater than five"
    })

Strategy

addValidationStrategy

A Strategy is a group of validation rules under a name space. Use of strategy gives one ability to provide namespaces to their validation rules. A strategy can be added and used as shown below. One can create own strategy by define strategy by creating a named JS object with validation rules attached to its key.

 Maanyakaran.addValidationStrategy(NumberStrategy)
 const constraints = {
    person: {
        age: "NumberStrategy:Found-110"
    }
 }

Refer to NumberStrategy to implement your own strategy.

Tests

Tests are run using jest, to run the tests use:

npm test

License (MIT)

Copyright (c) 2019 Maanyakaran <maanyakaran@gourav.info>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Dependents (0)

Package Sidebar

Install

npm i maanyakaran

Weekly Downloads

0

Version

1.2.0

License

MIT

Unpacked Size

30.3 kB

Total Files

12

Last publish

Collaborators

  • gouravnema
  • ashwinijalkote