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

@tictuk/json-field-schema-validation

v1.1.3

Published

JSON Field Schema Validation

Downloads

1,706

Readme

JSON Field Schema Validation Package

Installation

npm install @tictuk/json-field-schema-validation

Usage

Simple Example

  • Validate a single schema field
import {
  InputSchema,
  Lang,
  ValidateSchemaParams,
  Values,
  FieldPick,
  validateSchema,
} from '@tictuk/json-field-schema-validation';

const schema: InputSchema = {
  fields: [
    {
      name: 'fiscalNumber',
      label: {
        en_US: 'Fiscal Number',
        pt_PT: 'Número Fiscal',
      },
      validation: {
        rules: {
          required: true,
          minlength: 3,
        },
      },
    },
    {
      name: 'brazilCPF',
      label: {
        en_US: 'CPF',
        pt_PT: 'CPF',
      },
      validation: {
        rules: {
          cpf: {
            type: 'custom',
          },
        },
        messages: {
          'cpf.default': {
            en_US: 'I told ya valid cpf',
            pt_PT: 'I told ja validao cpf',
          },
        },
      },
    },
  ],
  validation: {
    messages: {
      internalServerError: {
        pt_PT: 'Internal Server Error',
        en_US: 'Internal Server Error',
      },
      stringEmpty: {
        pt_PT: '%label% is required',
        en_US: '%label% is required',
      },
      stringBase: {
        pt_PT: '%label% must be a valid string',
        en_US: '%label% must be a valid string',
      },
      numberBase: {
        pt_PT: '%label% must be a number',
        en_US: '%label% must be a number',
      },
      objectUnknown: {
        pt_PT: '%label% is not allowed',
        en_US: '%label% is not allowed',
      },
      anyInvalid: {
        pt_PT: '%label% contains an invalid value',
        en_US: '%label% contains an invalid value',
      },
      anyRequired: {
        pt_PT: '%label% is required',
        en_US: '%label% is required',
      },
      stringEmail: {
        pt_PT: '%label% must be a valid email',
        en_US: '%label% must be a valid email',
      },
      stringMin: {
        pt_PT: '%label% must be at least %limit% characters long',
        en_US: '%label% must be at least %limit% characters long',
      },
      stringMax: {
        pt_PT: '%label% must be less than or equal to %limit% characters long',
        en_US: '%label% must be less than or equal to %limit% characters long',
      },
      numberMin: {
        pt_PT: '%label% must be greater than or equal to %limit%',
        en_US: '%label% must be greater than or equal to %limit%',
      },
      numberMax: {
        pt_PT: '%label% must be less than or equal to %limit%',
        en_US: '%label% must be less than or equal to %limit%',
      },
      validCPF: {
        pt_PT: 'Por favor indique o CPF válido',
        en_US: 'Please enter a valid CPF number',
      },
    },
  },
};

const values: Values = {
  brazilCPF: '12345678909',
};

const lang: Lang = 'pt';

const pick: FieldPick = ['brazilCPF'];

const validateSchemaParams: ValidateSchemaParams = {
  schema,
  values,
  lang,
  pick,
};

const validateSchemaResponse = await validateSchema(validateSchemaParams);

if (!validateSchemaResponse.valid) {
  console.error('Error! Message: ' + validateSchemaResponse.errorMessage);
  return false;
}

return true;

Simplistic Example

  • Validate a single schema field
  • Only check valid status
  • Not supply error messages
import {
  InputSchema,
  Lang,
  ValidateSchemaParams,
  Values,
  FieldPick,
  validateSchema,
} from '@tictuk/json-field-schema-validation';
const schema: InputSchema = {
  fields: [
    {
      name: 'fiscalNumber',
      label: {
        en_US: 'Fiscal Number',
        pt_PT: 'Número Fiscal',
      },
      validation: {
        rules: {
          required: true,
          minlength: 3,
        },
      },
    },
    {
      name: 'brazilCPF',
      label: {
        en_US: 'CPF',
        pt_PT: 'CPF',
      },
      validation: {
        rules: {
          cpf: {
            type: 'custom',
          },
        },
      },
    },
  ],
};

const values: Values = {
  brazilCPF: '12345678909',
};

const lang: Lang = 'pt';

const pick: FieldPick = ['brazilCPF'];

const validateSchemaParams: ValidateSchemaParams = {
  schema,
  values,
  lang,
  pick,
};

const validateSchemaResponse = await validateSchema(validateSchemaParams);

return !!validateSchemaResponse.valid;

Complex Example

  • Validate all schema fields at once
  • Supply error messages in multiple languages
  • Filter for different kinds of errors
  • Use returned property value
  • Use optional satisfies keyword on the values and params (when the values are known in compile time) to access values by property name on the response.
import {
  InputSchema,
  Lang,
  ValidateSchemaParams,
  Values,
  validateSchema,
} from '@tictuk/json-field-schema-validation';

const schema: InputSchema = {
  fields: [
    {
      name: 'fiscalName',
      label: {
        en_US: 'Fiscal Name',
        es_ES: 'Nombre',
        pt_PT: 'Nome',
      },
      validation: {
        rules: {
          required: true,
          minlength: 0,
        },
      },
    },
    {
      name: 'fiscalNumber',
      label: {
        en_US: 'Fiscal Number',
        es_ES: 'Cedula o RUC',
        pt_PT: 'Número Fiscal',
      },
      validation: {
        rules: {
          required: true,
          minlength: 3,
        },
      },
    },
    {
      name: 'email',
      label: {
        en_US: 'Email',
        es_ES: 'Correo Electrónico',
        pt_PT: 'Correio Eletrônico',
      },
      validation: {
        rules: {
          required: true,
          email: true,
        },
      },
    },
    {
      name: 'phone',
      label: {
        en_US: 'Phone',
        es_ES: 'Teléfono',
        pt_PT: 'Telefone',
      },
      validation: {
        rules: {
          required: true,
          minlength: 3,
        },
        messages: {
          required: {
            en_US: 'Please enter your phone number',
            pt_PT: 'Desculpe escriba su numerao de telefono',
            es_ES: 'Por favor escriba su número de teléfono',
          },
          minlength: {
            en_US: 'I told ya at least 3 chars',
            pt_PT: 'I told ja ato leastao 3 chares',
            es_ES: 'I told ja ato leasto 3 chares',
          },
        },
      },
    },
    {
      name: 'ID',
      label: {
        en_US: 'I.D.',
        pt_PT: 'IDDñ',
      },
      validation: {
        rules: {
          number: true,
          min: 10000000,
          max: 999999999,
        },
      },
    },
  ],
  validation: {
    messages: {
      internalServerError: {
        pt_PT: 'Internal Server Error',
        es_ES: 'Error interno del servidor',
        en_US: 'Internal Server Error',
      },
      stringEmpty: {
        pt_PT: '%label% is required',
        es_ES: '%label% es obligatorio',
        en_US: '%label% is required',
      },
      stringBase: {
        pt_PT: '%label% must be a valid string',
        es_ES: '%label% debe ser una cadena de texto válida',
        en_US: '%label% must be a valid string',
      },
      numberBase: {
        pt_PT: '%label% must be a number',
        es_ES: '%label% debe ser un número válido',
        en_US: '%label% must be a number',
      },
      objectUnknown: {
        pt_PT: '%label% is not allowed',
        es_ES: '%label% no está permitido',
        en_US: '%label% is not allowed',
      },
      anyInvalid: {
        pt_PT: '%label% contains an invalid value',
        es_ES: '%label% contiene un valor no válido',
        en_US: '%label% contains an invalid value',
      },
      anyRequired: {
        pt_PT: '%label% is required',
        es_ES: '%label% es obligatorio',
        en_US: '%label% is required',
      },
      stringEmail: {
        pt_PT: '%label% must be a valid email',
        es_ES: '%label% debe ser una dirección de correo electrónico válida',
        en_US: '%label% must be a valid email',
      },
      stringMin: {
        pt_PT: '%label% must be at least %limit% characters long',
        es_ES: '%label% debe tener al menos %limit% caracteres',
        en_US: '%label% must be at least %limit% characters long',
      },
      stringMax: {
        pt_PT: '%label% must be less than or equal to %limit% characters long',
        es_ES:
          '%label% debe tener menos de %label% caracteres o %limit% caracteres como máximo',
        en_US: '%label% must be less than or equal to %limit% characters long',
      },
      numberMin: {
        pt_PT: '%label% must be greater than or equal to %limit%',
        es_ES: '%label% debe ser mayor o igual que %limit%',
        en_US: '%label% must be greater than or equal to %limit%',
      },
      numberMax: {
        pt_PT: '%label% must be less than or equal to %limit%',
        es_ES: '%label% debe ser menor o igual que %limit%',
        en_US: '%label% must be less than or equal to %limit%',
      },
      validCPF: {
        pt_PT: 'Por favor indique o CPF válido',
        es_ES: 'Por favor ingresa un npumero de CPF válido',
        en_US: 'Please enter a valid CPF number',
      },
    },
  },
};

const values = {
  fiscalName: 'abc',
  fiscalNumber: 'xyz',
  email: '[email protected]',
  phone: '123',
} satisfies Values; // Optional: can also specify type as Values

const lang: Lang = 'es';

const validateSchemaParams = {
  schema,
  values,
  lang,
} satisfies ValidateSchemaParams; // Optional: can also specify type as ValidateSchemaParams

const validateSchemaResponse = await validateSchema(validateSchemaParams);

if (!validateSchemaResponse.valid) {
  if (validateSchemaResponse.error instanceof ValidationError) {
    console.error('Error in validation: ' + validateSchemaResponse.error);
  } else {
    console.error('Internal error: ' + validateSchemaResponse.error);
  }

  return validateSchemaResponse.errorMessage;
}

for (const [key, value] of Object.entries(validateSchemaResponse.value)) {
  //...
}
console.log(validateSchemaResponse.value.fiscalName);
return validateSchemaResponse.value;