Themis is a validation and processing library that helps you always make sure your data is correct.

Overview

Dataffy Themis - The advanced validation library


Themis is a validation and processing library that helps you always make sure your data is correct.
· Dataffy

Table of Contents
  1. About The Project
  2. Getting Started
  3. Usage

About The Project

Themis is a flexible validation library built on 3 layers used for validation. Each upper layer is based on the previous layer and adds extra functionality.

Layers from top to bottom:

  • Schema + Fields - Used to validate and transform an entire object.
  • Processors - Used to validate and transform a value. Uses validators behind the scene
  • Validators - Used to validate a value against some requirements (e.g: max value, max length, etc.)

Getting Started

NPM

npm install @dataffy/themis

Yarn

yarn add @dataffy/themis

Usage

Schemas

Schemas are used to validate and transform an object to the desired representation

import {
  DateField,
  IntegerField,
  FloatField,
  Schema,
  StringField,
} from "@dataffy/themis";

export type CreateEventPayload = {
  name: string;
  price: number;
  date: Date;
  maxCapacity: number;
};

export class CreateEventSchema extends Schema<CreateEventPayload> {
  @StringField({
    maxLength: 100,
  })
  name: string;

  @FloatField({
    minValue: 5.5,
  })
  price: number;

  @DateField({
    formats: ["dd/MM/yyyy"],
  })
  date: Date;

  @IntegerField({
    required: false,
    nullable: true,
    fromField: "max_capacity",
  })
  maxCapacity: number;
}

const payload = {
  name: "Dataffy Themis",
  price: 0,
  date: "01/01/2022",
  max_capacity: 40,
};
const createUserSchema = new CreateUserSchema(payload);

createUserSchema
  .validate()
  .then(() =>
    console.log(
      "Validation was successful. Use .toData() to get the validated data"
    )
  )
  .catch((error) => console.log("Validation failed"));

const validatedData = createUserSchema.toData();

Fields

Fields are decorators used on Schema properties to annotate how the field needs to be processed. Behind the scenes, the fields specify which Processor is used for the field type.

Field Decorator Configuration:

  • fromField - Specifies from which field the value will be taken, processed and placed in the property name. e.g: Using a decorator with fromField: first_name on a property firstName will process the value and place it in the firstName property on the validated data

Example implementation of a Decorator. This example can be used for creating custom decorators:

export const StringField: ValidationField<StringFieldConfig> =
  (configuration?: DecoratorFieldConfig<StringFieldConfig>) =>
  (target: object, propertyKey: string): void => {
    registerField(target, propertyKey, configuration, StringFieldProcessor);
  };

Nested Fields

Nested fields allow specifying a Schema that is used for validating and transforming the nested object.

@NestedField({ schema: FileSchema })
profileImage: FileSchema;

Processors

Processors are used to validate and transform a specific value into the desired one.

Generic Field Configurations:

  • required - Specifies if the field is required. Default value is true
  • nullable - Specifies if the field is nullable. Default value is true
  • validators - Extra validators against which the value is checked

Each field can have extra field configurations.

Field Processor Configuration
@StringField() StringFieldProcessor
  • maxLength - The max length allowed for the field
  • minLength - The min length allowed for the field
@BooleanField() BooleanFieldProcessor
@DateField() DateFieldProcessor
  • formats - Array with the accepted string formats for the date
@IntegerField() IntegerFieldProcessor
  • maxValue - The max value allowed for the field
  • minValue - The min value allowed for the field
@FloatField() FloatFieldProcessor
  • maxValue - The max value allowed for the field
  • minValue - The min value allowed for the field
@EmailField() EmailFieldProcessor
@JsonField() JsonFieldProcessor
@ArrayField() ArrayFieldProcessor
  • child - The type of values the array has. It can be a Schema class or Processor class
  • childConfig - Used to specify the config for the child, if the child is a processor class

Creating a custom processor:

import { FieldProcessor, MinValueValidator } from "@dataffy/themis";

export type CustomFieldConfig = FieldConfig &
  Partial<{
    // Your field config
  }>;

export class CustomProcessor extends FieldProcessor<
  CustomFieldConfig,
  number,
  number
> {
  toInternalValue(data: number): number {
    // Validate value and transform it to expected response
  }

  initialiseValidators(): void {
    // Push validators into the validators property based on the configuration properties
    if (this.configuration.minValue) {
      this.validators.push(new MinValueValidator(this.configuration.minValue));
    }
  }
}

Validators

Validators are the basic unit for the library. They are used for checking if a value matches the expected requirements.

const maxLength = 50;
const validator = new MaxValueValidator(maxLength);
validator.validate(30);

License

Distributed under the ISC License. See LICENSE for more information.

Comments
  • Add ability input custom validators for the fields

    Add ability input custom validators for the fields

    Add the ability to input custom validators for fields that will not override the default preset validators but will be both applied.

    const isValidString = (value: string) => !value.isEmpty()
    @StringField({validators: [isValidString]})
    
    enhancement 
    opened by RaduMolnar99 2
  • Add ArrayField and ArrayProcessor

    Add ArrayField and ArrayProcessor

    • Add ArrayField and ArrayProcessor
    • Move context from validate function to Schema and Processor constructors
    • Make Schema functions return Promise
    • Modify ProcessorValidateError to handle multiple types

    Closes #27

    opened by dariusmb 0
  • Add ArrayField & ArrayProcessor

    Add ArrayField & ArrayProcessor

    Description Add the ArrayField decorator and create the processor for the field.

    The field should allow specifying what is the child value that is going to be validated. It is either a primitive value (another field) or another schema.

    opened by dariusmb 0
  • Add EnumField & EnumProccessor

    Add EnumField & EnumProccessor

    Description Add the EnumField decorator and create the processor for the field.

    The field's toInternalValue will transform the input string into the the Enum type and check if it is a valid value for the enum.

    Configuration: enum - The enum that you want the string to be checked against.

    enhancement 
    opened by RaduMolnar99 0
  • Add fromField config for the decorator config

    Add fromField config for the decorator config

    The field decorators need to allow the possibility to specify from where that field gets the value from the input data.

    Example usage:

    @StringField({fromField: 'last_name'})
    lastName: string;
    
    enhancement 
    opened by dariusmb 0
  • Improve error throwing

    Improve error throwing

    The package has 3 levels of validations:

    • Validator level - throws ValidateError which has a message
    • Processor level - validates the field by applying all the validators. At this level, an array with all the ValidateError messages must be constructed and an ProcessorValidateError is thrown with the array
    • Schema validate - validates all the fields and constructs an object containing as keys the properties and as value the array of errors. The thrown error must be ValidateError
    enhancement 
    opened by dariusmb 0
  • Make the Validator constructor public, so we don't need to override it in the child class

    Make the Validator constructor public, so we don't need to override it in the child class

    Make the Validator constructor public instead of protected.

    Current implementation

    The validator constructor is protected, and we always need to override it in the child validator

    class MyValidator extends Validator<string> {
      constructor() {
        super();
      }
    }
    .
    class MySchema extends Schema {
      @StringField({ validators: [new TimeZoneValidator()]})
      myField: string
    }
    

    We are forced by typescript to override the constructor, because we cannot use new TimeZoneValidator(), if the constructor is protected

    Proposed solution

    Make the constructor public, so we don't need to override it.

    enhancement 
    opened by razvanbretoiu 0
  • Inherit fields from parent classes

    Inherit fields from parent classes

    Description

    Inherit the fields from all parent classes.

    e.g:

    class BaseSchema extends Schema<BasePayload> {
      @StringField()
      parentField: string;
    }
    
    class ChildSchema extends Schema<ChildPayload> {
      @IntegerField()
      extraField: string;
    }
    

    When the ChildSchema is validated, it should also validate the parentField

    enhancement 
    opened by dariusmb 0
  • Add Polymorphic Schema

    Add Polymorphic Schema

    We should have a class PolymorphicSchema which should have the following:

    • a lookup field which by default should have the value type
    • an object field which will store a key value. The value will be a schema and the key should be used to determine which schema we are using.
    enhancement 
    opened by RaduMolnar99 0
Owner
Dataffy
Dataffy
The most powerful data validation library for JS

joi The most powerful schema description language and data validator for JavaScript. Installation npm install joi Visit the joi.dev Developer Portal f

Sideway Inc. 19.6k Jan 4, 2023
Lightweight and powerfull library for declarative form validation

Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?

Illia 49 May 13, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
Lightweight JavaScript form validation library inspired by CodeIgniter.

validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r

Rick Harrison 2.6k Dec 15, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
A simple credit cards validation library in JavaScript

creditcard.js A simple credit cards validation library in JavaScript. Project website: https://contaazul.github.io/creditcard.js Install creditcard.js

ContaAzul 323 Jan 7, 2023
v8n ☑️ ultimate JavaScript validation library

The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr

Bruno C. Couto 4.1k Dec 30, 2022
A lightweight NodeJS library for strict mime-type validation on streams

A lightweight NodeJS library for strict mime-type validation on streams. It gets a ReadableStream and decets the mime-type using its Magic number and validates it using the provided allowed and forbidden lists; If it's allowed it will pass it to the created WritableStreams and if it's not it will throw an error.

CEO of Death Star 9 Apr 3, 2022
Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is a powerful tool to sanitize and validate JS objects. It's designed to work both client-side and server-side and to be scalable wit

null 494 Oct 3, 2022
:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator ✅ Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Netto Farah 160 Dec 14, 2022
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

upjs 314 Dec 26, 2022
TypeScript-first schema validation for h3 and Nuxt applications

h3-zod Validate h3 and Nuxt 3 requests using zod schema's. Install npm install h3-zod Usage import { createServer } from 'http' import { createApp } f

Robert Soriano 48 Dec 28, 2022
Simple, smart and pleasant validation solution.

nice-validator Simple, smart and pleasant validation solution. Download the latest release or install package via npm or bower $ npm install nice-vali

Jony 608 Nov 18, 2022
String validation

validator.js A library of string validators and sanitizers. Strings only This library validates and sanitizes strings only. If you're not sure if your

null 20.7k Jan 5, 2023
Cross Browser HTML5 Form Validation.

Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1

Jay Morrow 279 Nov 1, 2022
jQuery form validation plugin

jQuery.validationEngine v3.1.0 Looking for official contributors This project has now been going on for more than 7 years, right now I only maintain t

Cedric Dugas 2.6k Dec 23, 2022
Dead simple Object schema validation

Yup Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existin

Jason Quense 19.2k Jan 2, 2023
📫 Offline email validation - JS or TS

email-seems-valid An offline check to see if an email seems valid. Contains TS or JS packages for browser or Node.js emailSeemsValid('[email protected]')

earnifi 12 Dec 25, 2022