2.3.1 • Published 10 months ago

@amateury/lettuce v2.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Lettuce 2.2

build develop Coverage Status

It is a library that allows a rigorous validation of the data, according to a specific pattern (a scheme).

Installation

requires Node.js v12+.

npm i @amateury/lettuce --save

Usage

Validator

import Lettuce from "@amateury/lettuce";

const scheme = [
  {
    target: "email",
    type: String,
    required: true,
    strict: true,
    regex: /^[\w-\\.]+@([\w-]+\.)+[\w-]{2,4}$/g,
  },
  {
    target: "name",
    type: String,
    required: false,
    strict: false,
    min: 2,
    max: 50,
  },
  {
    target: "password",
    type: String,
    required: false,
    strict: false,
    min: 8,
  }
];

const lettuce = new Lettuce(scheme);

const values = {
  email: "albert@lettuce.com",
  name: "Albert",
  password: "$b4fei"
}

lettuce.parser(values).then((data) => {
  console.log(data); // successful
}).catch((e) => {
  console.log(e); // Error response
});

Example 1

The <-parser-> method executes the data validation, if it is successful, the response message is the data sent to validation, otherwise it generates an exception:

Response successful

{
  "email": "albert@lettuce.com",
  "name": "Albert",
  "password": "$b4fei"
}

Example 1.1

Response error

In the event that we send, we request that the password contain a minimum of 8 characters

[
  {
    "error": [
      "password_min"
    ],
    "target": "password",
    "value": "true"
  }
]

Example 1.2

Schemes

A schema represents a validation element, for example:

Example 2

  {
    target: "name",
    type: String,
    required: false,
    strict: false,
    min: 2,
    max: 50,
    regex: /^[\w-\\.]+@([\w-]+\.)+[\w-]{2,4}$/g
  }

such a schema contains properties, each with its own validation target, for example

Properties of a schema

propertydescription
typeDefines the type of data to validate (String, Number, Array, Object, Boolean, etc).
required(boolean) true for required, false for not required. Default is true
min(number) determines the minimum value, if it is a string it will validate the number of characters, in the case of a number it will validate its value.
max(number) determines the maximum value, the same as the min property but pointing to a maximum value.
valueassigns a value, it has to be of the same declared type, it can be a function with a return value: () => uuid; o value: 'developer', when passing a function it receives the original value as a parameter, declared in the values to be validated (value) => value + '_01'.
strict(boolean) strictly determines data type validation. Default is true
regexValidate using regular expression.
comparecompare the value of an objective, with another value, it can be a comparison of equals or different (equal, distinct)
message(Object or string) Create custom error messages

Using properties in the schema: some examples

required and strict:

Add a value for a specific act: it is possible to change the validation behavior to the opposite value, for example:

{ 
  target: "phone",
  required: { put: false, default: true },
  strict: { put: false, default: true },
}

call:

lettuce.act("put").parser(values).then((data) => {
  console.log(data); // successful
}).catch((e) => {
  console.log(e); // Error response
});

type:

Of all the properties, type is the only one required. The data type is defined with the containers. example of javascript primitives:

{ target: "phone", type: String }

It is also possible to define multiple data types, in this case allowing string and null data types

{ target: "phone", type: [String, null] }

For the case of choice we use it in this way

{ target: "phone", type: ["active", "inactive"] }

For a bit more flexibility, it is possible to configure a custom data type

class MyCustomValidation {
  static __validate__(val: string) {
    return typeof val === "string";
  }
}

And in this way pass MyCustomValidation as the data type to validate

{ target: "phone", type: MyCustomValidation }

strict:

if strict is true, and the type is a String, the value to validate is a numeric data, it will not pass the validation, but if strict is false, it will accept the data type as a string if its conversion to a string is possible; otherwise it will throw an invalid data type error.

import Lettuce, { IScheme, TValues } from "@amateury/lettuce";

function example(values: TValues[]) {
  const sheme: IScheme[] = [
    { target: "phone", type: String, strict: true }
  ]
  const lettuce = new Lettuce(sheme);
  lettuce.parser(values).then((data) => data).catch((e) => {
    console.log(e); // Error response
  });
}
example({ phone: 20 });

compare:

Compare two values (equal, distinct)

import Lettuce, { IScheme, TValues } from "@amateury/lettuce";

function example(values: TValues[]) {
  const sheme: IScheme[] = [
    { target: "phone", type: String, required: true, strict: true },
    {
      target: "phone2",
      type: String,
      required: true,
      strict: true,
      compare: {
        distinct: "phone",
      },
    }
    { target: "password", type: String, required: true, strict: true },
    {
      target: "confirmPassword",
      type: String,
      required: true,
      strict: true,
      compare: {
        equal: "password",
      },
    }
  ]
  const lettuce = new Lettuce(sheme);
  lettuce.parser().then((data) => data).catch((e) => {
    console.log(e); // Error response
    /**
     * [
     * {
     *   "error": [
     *      "phone2_compareDistinct",  
     *    ],
     *    "target": "phone2"
     *    "value": "3122345643"
     *  },
     *  {
     *    "error": [
     *      "confirmPassword_compareEqual",  
     *    ],
     *    "target": "confirmPassword"
     *    "value": "$b4feiG*LNzq."
     *  }
     * ]
     */
  });
}
example({
    password: "$b4feiG*LNzq",
    confirmPassword: "$b4feiG*LNzq.",
    phone: "3122345643",
    phone2: "3122345643",
});

message:

Allows you to create custom error messages

import Lettuce, { IScheme, TValues } from "@amateury/lettuce";

function example(values: TValues[]) {
  const sheme: IScheme[] = [
    {
      target: "username",
      type: String,
      required: true,
      strict: true,
      message: (message, { validKey }) => {
        if (validKey === "required") {
          return "username_is_required";
        } else {
          return message;
        }
      }
    },
    {
      target: "email",
      type: String,
      required: true,
      strict: true,
      min: 125,
      regex: /^[\w-\\.]+@([\w-]+\.)+[\w-]{2,4}$/g,
      message: "Error validation"
    },
    {
      target: "phone",
      type: String,
      max: 10,
      min: 10,
      required: false,
      strict: false,
      message: {
        max: "phone_max_10"
      }
    },
    {
      target: "fullname",
      type: String,
      required: true,
      strict: true,
      min: 125,
    },
    { target: "password", type: String, required: true, strict: true },
    {
      target: "confirmPassword",
      type: String,
      required: true,
      strict: true,
      compare: {
        equal: "password",
      },
      message: {
        compareEqual: "Passwords do not match"
      }
    }
  ]
  const lettuce = new Lettuce(sheme);
  lettuce.parser({ phobe: "30012343211", email: "lettuce.mail.com" }).then((data) => data).catch((e) => {
    console.log(e); // Error response
    /**
     * [
     *  {
     *    "error": [
     *      "username_is_required", 
     *      "username_type"    
     *    ],
     *    "target": "username"
     *  },
     *  {
     *    "error": [
     *      "phone_max_10"   
     *    ],
     *    "target": "phone"
     *    "value": "30012343211"
     *  },
     *  {
     *    "error": [
     *      "Error validation"   
     *    ],
     *    "target": "phone"
     *    "value": "lettuce.mail.com"
     *  },
     *  {
     *    "error": [
     *      "fullname_required"   
     *    ],
     *    "target": "fullname"
     *  },
     *  {
     *    "error": [
     *      "Passwords do not match",  
     *    ],
     *    "target": "confirmPassword"
     *    "value": "$b4feiG*LNzq."
     *  }
     * ]
     */
  });
}
example({ phone: 20 });

Using strict cycle

strictCycle allows you to generate errors strictly to the first error generated or according to the interval of errors per schema. Each schema can generate a group of errors that are grouped in an object with the information of the errors that is an interval, strictCycle in true represents interval 1.

Example 2.1

import Lettuce, { IScheme, TValues } from "@amateury/lettuce";

async function example(values: TValues[]) {
  const schemas = [
    {
      target: "email",
      type: String,
      required: true,
      strict: true,
      regex: /^[\w-\\.]+@([\w-]+\.)+[\w-]{2,4}$/g,
    },
    {
      target: "age",
      type: Number,
      min: 18,
    },
  ]
  try {
    const lettuce = new Lettuce(schemas, {
      strictCycle: true,
    });
    await lettuce.parser({ email: "lettuce", age: 15 });
  } catch (e) {
    console.log(e.length); // 1
  }
}
example({ phone: 20 });

strictCycle in interval 2:

import Lettuce, { IScheme, TValues } from "@amateury/lettuce";

async function example(values: TValues[]) {
  try {
    const lettuce = new Lettuce(schemas, {
      strictCycle: 2,
    });
    await lettuce.parser({ email: "lettuce", age: 15 });
  } catch (e) {
    console.log(e.length); // 2
  }
}
example({ phone: 20 });

New functionality

act: Allow configuring a run where required or strict values can be flexible depending on the use case.

Contribute

See contributor guide

Persons

Person in charge Bryant Salgado

License

MIT

Free Software

2.2.1

10 months ago

2.3.1

10 months ago

2.1.2

2 years ago

2.2.0

2 years ago

2.0.2

2 years ago

2.1.4

2 years ago

2.1.3

2 years ago

2.1.5

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago