npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@amateury/lettuce

v2.3.1

Published

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

Downloads

55

Readme

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: "[email protected]",
  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": "[email protected]",
  "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

| property | description | |----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | type | Defines 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. | | value | assigns 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 | | regex | Validate using regular expression. | compare | compare 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