Package to use decorators with validatorJS

I just created a package that work with validatorJS and Typescript decorators to validate your classes.

Validation using decorators with validatorjs
Validation using decorators with validatorjs

Validation inside function#

I was validating the parameters of the function get in one of this way. It's works but look like the code is unclean.

class Paginate<T> {
private readonly query: SelectQueryBuilder<T>;
constructor(query: SelectQueryBuilder<T>) {
this.query = query;
}
async get(limit: number, page: number) {
const errors = await getFieldErrors(
{ limit, page },
{
limit: 'required|integer|min:1',
page: 'required|integer|min:1',
},
);
if (errors) {
throw new ValidatorError(errors);
}
const total = await this.query.getCount();
...
}
}

Validation using decorator#

Validate a class function#

It works well, but I decorators make it looks clean and easy to read:

class Paginate<T> {
private readonly query: SelectQueryBuilder<T>;
constructor(query: SelectQueryBuilder<T>) {
this.query = query;
}
@validateAsync()
async get(
@arg('limit', 'required|integer|min:1') limit: number,
@arg('page', 'required|integer|min:1') page: number,
) {
const total = await this.query.getCount();
...
}
}

Validate a class constructor and properties#

Also, it works for constructor or properties:

@validateClass()
class Example {
@prop('email')
public readonly email: string;
public readonly password: string;
constructor(
@arg('email', 'email|required') email: string,
@arg('password', 'string|required') password: string,
) {
this.email = email;
this.password = password;
}
}

Install#

To install run one of this instructions:

  • npm install validatorjs-decorator
  • yarn add validatorjs-decorator

All the rules availables are in the validatorJS repository. The code of validatorjs-decorators package is in my github.