zafiro-validators
v1.1.0 validation
zafiro-validators
Decorator based interface for Joi.
:warning: 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,
"[email protected]"
);
const result1 = validate(validUser);
expect(result1.error).to.eql(null);
const invalidUser1 = new User(
"root",
"secret$",
"token",
1989,
"[email protected]"
);
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: "[email protected]"
};
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.
npm i zafiro-validators
Metadata
- MIT
- Whatever
- Remo H. Jansen
- released 12/5/2017