zafiro-validators
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

zafiro-validators

Join the chat at https://gitter.im/inversify/InversifyJS npm version Build Status Dependencies img Known Vulnerabilities Twitter Follow

Decorator based interface for Joi.

⚠️ This library is part of the Zafiro ecosystem but it is standalone and can be used on its own.

Installation

npm install zafiro-validators reflect-metadata

The basics

import { shouldBe, a, validate } from "zafiro-validators";
 
class User {
    @mustBe(a.string().alphanum().min(3).max(30).required())
    public username: string;
    @mustBe(a.string().regex(/^[a-zA-Z0-9]{3,30}$/))
    public password: string;
    @mustBe([a.string(), a.number()])
    public accessToken: string|number;
    @mustBe(a.number().integer().min(1900).max(2013))
    public birthyear: number;
    @mustBe(a.string().email())
    public email: string;
    public constructor(
        username: string,
        password: string,
        access_token: string|number,
        birthyear: number,
        email: string
    ) {
        this.username = username;
        this.password = password;
        this.accessToken = accessToken;
        this.birthyear = birthyear;
        this.email = email;
    }
}
 
const validUser = new User(
    "root",
    "secret",
    "token",
    1989,
    "test@test.com"
);
 
const result1 = validate(validUser);
expect(result1.error).to.eql(null);
 
const invalidUser1 = new User(
    "root",
    "secret$",
    "token",
    1989,
    "test@test.com"
);
 
const result2 = validate(invalidUser1);
expect(result2.error.message).to.eql(
    `child "password" fails because ["password" with value "secret$" ` +
    `fails to match the required pattern: /^[a-zA-Z0-9]{3,30}$/]`
);
 
const invalidUser2 = new User(
    "root",
    "secret",
    "token",
    1989,
    "test@@test.com"
);
 
const result3 = validate(invalidUser2);
expect(result3.error.message).to.eql(
    `child "email" fails because ["email" must be a valid email]`
);

You can also invoke validate for object literals but you will need to pass the expected schema as validate(literal, Class):

const user2 = {
    username: "root",
    password: "secret$",
    accessToken: "token",
    birthyear: 1989,
    email: "test@test.com"
};
 
const result2 = validate(user2, User);
expect(result2.error.message).to.eql(
    `child "password" fails because ["password" with value "secret$" ` +
    `fails to match the required pattern: /^[a-zA-Z0-9]{3,30}$/]`
);

You can learn more about the Joi API here.

Readme

Keywords

Package Sidebar

Install

npm i zafiro-validators

Weekly Downloads

4

Version

1.1.0

License

MIT

Last publish

Collaborators

  • remojansen