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

joiful

v3.0.2

Published

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

Downloads

23,473

Readme

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.