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

json2validations

v0.1.4

Published

I simple JSON schema for form validations

Downloads

22

Readme

json2validations is a schema builder and Schema Definition the main purpose is to create form validations from a JSON. It allows implementing complex data validation logic via declarative schemas for your form data, without writing code.

Table of contents

  1. Install
  2. Builder
  3. Schema
  4. Config
  5. Examples
    • Using native types
    • Using custom types

Install

yarn add json2validations

Example

Here an example using react-hook-form to handle common scenarios

CodeSanbox

Builder

buildSchema method does one simple task, validates the fields against the JSON and returns all the fields in case everything went well or throws and exception in case of error. This method can be configured throught a config object, this will allow you to override and extend from native types to create any validation or pattern (string only)

buildSchema(schema, fields, config);

Schema

The schema is the heart of the system, other JSON schema validations libraries implement JSONSchema Specification to advantage of its standarized interface, that result loosing scope trying to solve a lot of scenarios. This new schema its aimed to solve form validations only, giving you more flexibility making custom validations and more.

Let's get started understanding how all the pieces go together into the schema.

All in the schema are fields, to explain that to the schema builder you have to add the fields key to your JSON, every key will be a field, there's where you add the form fields you want to validate, every key name has to be a field name in your form.

{
    fields: {
        [FIELD_NAME]: {
            type: '',/* string | number | date | boolean */
            errorMessages: {
                [ERROR_NAME]: "some custom error message" /* string */
            },
            required: 'false',/* boolean */
            validations: {
                default: {
                    /* number type only */
                    maximum: /* number */
                    minimum: /* number */
                    /* string type only */
                    maxLength: /* number */
                    minLength: /* number */
                    patterns: /* [customRegEx | customPattern | "onlyLetters" ] */
                },
                extends: /* [customValidationName, customValidationName2] */
            }
        }
     }
}

Config

The config object will allow you to extend the functionality of the builder as create your custom types or hook up to the build flow, also create transformations before and after validations are executed

Here you define all the patterns, validations and transformations you'll expect for every field type To add your custom functionality you have to match the name type, defaultFieldTypes its where all the types are defined Type interface allows a few keys:

from name type to extend validations from

validations object of custom validations

  • patterns (string only) an Array of custom patterns
  • extends here define your custom validation functions

transformations object to apply value transformations before and after validations

  • before an Array of transformations to be executed before validations
  • after an Array of transformations to be executed after validations
const config = {
  defaultFieldTypes: {
    /* name type (string, number...)*/
    [string | number | boolean | date]: {
      from: "string | number | boolean | date",
      validations: {
          patterns: [function someCustomPattern(field, config) {}],
        extends: {
          someCustomValidation: (field, config) {}
        }
      },
      transformations: {
        after: [function someTransformation(value) {}: any],
      },
    },
};

Examples

  • native validations

Imagine you have a field that accepts less than 10 characters, that will look something like this

/* this is your form fields */
const fields = {
  testingField: "this is longer than 10",
};
/* this is your JSON schema (coming from an API maybe...) */
const schema = {
  fields: {
    testingField: {
      type: "string",
      validations: {
        default: {
          maxLength: 10,
        },
      },
    },
  },
};

const fields = buildSchema(schema, fields);

// OUTPUT
// FormErrors: testinField max length of 10 exceded
  • custom validations

Imagine you have a date field that validates if the value entered is this month or this year. To create that custom validation just 2 steps are needed.

  1. add your custom validation into extends
  2. pass your error with config.setError
/* config to schema builder */
  const config = {
        defaultFieldTypes: {
          date: {
            validations: {
              extends: {
                notThisMonthAndYear: (field, config) => {
                  if (isThisMonth(field.value) && isThisYear(field.value)) {
                    config.setError(new ValidationError({
                      path: field.key,
                      message: `${field.key} must not be this month and year`,
                    });
                  })
                },
              },
            },
          },
        },
      };

/* these are  your form fields */
const fields = {
  testingField: new Date(),
};
/* this is your JSON schema (coming from an API maybe...) */
 const schema = {
        fields: {
          testingField: {
            type: "date",
            validations: {
              extends: ["notThisMonthAndYear"],
            },
          },
        },
      };

const fields = buildSchema(schema, fields, config);