Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

joiful

joiful-ts21.7kMIT3.0.2TypeScript support: included

TypeScript Declarative Validation. Decorate your class properties to validate them using Joi.

class, constrain, constraint, declarative, decorator, decorators, joi, model, schema, tsdv, tsdv-joi, typescript, validate, validator, validators, validation

readme


TypeScript Declarative Validation for Joi


npm version GitHub Actions Build Status codecov Dependabot Status

Why Joiful?

This lib allows you to apply Joi validation constraints on class properties, by using decorators.

This means you can combine your type schema and your validation schema in one go!

Calling Validator.validateAsClass() allows you to validate any object as if it were an instance of a given class.

Installation

npm add joiful reflect-metadata

Or

yarn add joiful reflect-metadata.

You must enable experimental decorators and metadata in your TypeScript configuration.

tsconfig.json

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  }
}

Basic Usage

Ensure you import reflect-metadata as the first import in your application's entry point.

index.ts

import 'reflect-metadata';

...

Then you can start using joiful like this.

import * as jf from 'joiful';

class SignUp {
  @jf.string().required()
  username: string;

  @jf
    .string()
    .required()
    .min(8)
  password: string;

  @jf.date()
  dateOfBirth: Date;

  @jf.boolean().required()
  subscribedToNewsletter: boolean;
}

const signUp = new SignUp();
signUp.username = 'rick.sanchez';
signUp.password = 'wubbalubbadubdub';

const { error } = jf.validate(signUp);

console.log(error); // Error will either be undefined or a standard joi validation error

Validate plain old javascript objects

Don't like creating instances of classes? Don't worry, you don't have to. You can validate a plain old javascript object as if it were an instance of a class.

const signUp = {
  username: 'rick.sanchez',
  password: 'wubbalubbadubdub',
};

const result = jf.validateAsClass(signUp, SignUp);

Custom decorator constraints

Want to create your own shorthand versions of decorators? Simply create a function like below.

customDecorators.ts

import * as jf from 'joiful';

const password = () =>
  jf
    .string()
    .min(8)
    .regex(/[a-z]/)
    .regex(/[A-Z]/)
    .regex(/[0-9]/)
    .required();

changePassword.ts

import { password } from './customDecorators';

class ChangePassword {
  @password()
  newPassword: string;
}

Validating array properties

class SimpleTodoList {
  @jf.array().items(joi => joi.string())
  todos?: string[];
}

To validate an array of objects that have their own joiful validation:

class Actor {
  @string().required()
  name!: string;
}

class Movie {
  @string().required()
  name!: string;

  @array({ elementClass: Actor }).required()
  actors!: Actor[];
}

Validating object properties

To validate an object subproperty that has its own joiful validation:

class Address {
  @string()
  line1?: string;

  @string()
  line2?: string;

  @string().required()
  city!: string;

  @string().required()
  state!: string;

  @string().required()
  country!: string;
}

class Contact {
  @string().required()
  name!: string;

  @object().optional()
  address?: Address;
}

Got a question?

The joiful API is designed to closely match the joi API. One exception is validating the length of a string, array, etc, which is performed using .exactLength(n) rather than .length(n). If you're familiar with the joi API, you should find joiful very easy to pickup.

If there's something you're not sure of you can see how it's done by looking at the unit tests. There is 100% coverage so most likely you'll find your scenario there. Otherwise feel free to open an issue.

Contributing

Got an issue or a feature request? Log it.

Pull-requests are also very welcome.

Alternatives

  • class-validator: usable in both Node.js and the browser. Mostly designed for validating string values. Can't validate plain objects, only class instances.
  • joi-extract-type: provides native type extraction from Joi Schemas. Augments the Joi type definitions.
  • typesafe-joi: automatically infers type information of validated objects, via the standard Joi schema API.

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

3.0.2 (2021-04-24)

3.0.1 (2021-04-24)

3.0.0 (2021-01-30)

⚠ BREAKING CHANGES

Co-authored-by: Benji codeandcats@gmail.com

Features

  • core: upgrade to @hapi/joi 16.0.0 (edbd4b2)
  • core: upgrade to sideway/joi 17.3.0 (e3def02)

2.0.1 (2020-04-27)

Bug Fixes

  • validation: issue 117: address feedback from code review (76cdcaf)
  • validation: issue 117: validator now accepts custom joi (505f9cd)

2.0.0 (2020-03-05)

Features

  • add getSchema & hasSchema functions (3e9f9f5)

1.1.9 (2019-12-07)

1.1.8 (2019-12-07)

1.1.7 (2019-12-07)

1.1.6 (2019-10-23)

1.1.5 (2019-10-23)

1.1.4 (2019-10-23)

1.1.3 (2019-10-17)

1.1.2 (2019-10-13)

1.1.1 (2019-10-13)

1.1.0 (2019-10-05)

Bug Fixes

  • build: run check in precommit (08a6497)
  • core: remove nested. replaced by object(Class) (679c42c)
  • core: update to require node 8.10 (49f32da)
  • test: fix bad calls in tests (0c0281f)
  • test: fix path to tsconfig file for tests (58e61c8)
  • test: rename fluent.ts to fluent.test.ts (cb746bb)
  • test: rename number.ts to number.test.ts (597aeb5)

Features

  • arrays: add fluent api syntax to Ordered decorator (f0885eb)
  • core: add fluent api to Items decorator (484b2c9)
  • core: ensure Joiful is used only with compatible joi versions (5ff4dae)
  • core: export decorators for default instance (67addd8)
  • core: export validation funcs from index.ts (00dc37f)
  • core: fluent api for individual schema decorators (0ac8efd)
  • core: new fluent decorator interface (7991044)
  • core: support fluent api via Joi decorator (606b151)
  • core: upgrade to joi 15, make joi normal dependency (1314228)
  • lint: add formatting linting rules (025d242)
  • tests: expect(x).toBeValid() will now display the candidate that failed (3289111)

1.0.0 (2019-08-30)

Bug Fixes

  • build: run check in precommit (08a6497)
  • core: remove nested. replaced by object(Class) (679c42c)
  • core: update to require node 8.10 (49f32da)
  • test: fix bad calls in tests (0c0281f)
  • test: fix path to tsconfig file for tests (58e61c8)
  • test: rename fluent.ts to fluent.test.ts (cb746bb)
  • test: rename number.ts to number.test.ts (597aeb5)

Features

  • arrays: add fluent api syntax to Ordered decorator (f0885eb)
  • core: add fluent api to Items decorator (484b2c9)
  • core: ensure Joiful is used only with compatible joi versions (5ff4dae)
  • core: export decorators for default instance (67addd8)
  • core: export validation funcs from index.ts (00dc37f)
  • core: fluent api for individual schema decorators (0ac8efd)
  • core: new fluent decorator interface (7991044)
  • core: support fluent api via Joi decorator (606b151)
  • core: upgrade to joi 15, make joi normal dependency (1314228)
  • lint: add formatting linting rules (025d242)
  • tests: expect(x).toBeValid() will now display the candidate that failed (3289111)