AJV beta

This tutorials show you, how you can validate your data with decorators.

Validation feature use Ajv and json-schema to perform the model validation.

Installation

Before using the validation decorators, we need to install the ajv module.

npm install --save ajv

Then import @tsed/ajv in your ServerLoader:

import {ServerLoader, ServerSettings} from "@tsed/common";
import "@tsed/ajv"; // import ajv ts.ed module

@ServerSettings({
    rootDir: __dirname
})
export class Server extends ServerLoader {

}

The AJV module allows a few settings to be added through the ServerSettings (all are optional):

  • options, are AJV specific options passed directly to the AJV constructor,
  • errorFormat, can be used to alter the output produced by the AjvService.

The error message could be changed like:

import {ServerLoader, ServerSettings} from "@tsed/common";
import "@tsed/ajv"; // import ajv ts.ed module

@ServerSettings({
    rootDir: __dirname,
     ajv: {
       errorFormat: (error) => `At ${error.modelName}${error.dataPath}, value '${error.data}' ${error.message}`,
       options: {verbose: true}
    },
})
export class Server extends ServerLoader {

}

Decorators

Ts.ED given some decorators to write your validation model:

Examples

Model validation

A model can used on a method controller along with @BodyParams or other decorators, and will be validated by Ajv.

import {Required, MaxLength, MinLength, Minimum, Maximum, Format, Enum, Pattern, Email} from "@tsed/common";

export class CalendarModel {
    
    @MaxLength(20)
    @MinLength(3)
    @Required()
    title: string;

    @Minimum(0)
    @Maximum(10)
    rating: number;

    @Email()
    email: string;

    @Format("date")  // or date-time, etc...
    createDate: Date;
    
    @Pattern(/hello/)
    customInput: string;
    
    @Enum("value1", "value2")
    customInput: "value1" | "value2";
}

All validation decorators are compatible with the Swagger documentation.

Validation error

When a validation error occur, AJV generate an errors list with a full description like this:

[
  {
    "keyword": "minLength",
    "dataPath": ".password",
    "schemaPath": "#/properties/password/minLength",
    "params": {"limit": 6},
    "message": "should NOT be shorter than 6 characters",
    "modelName": "User"
  }
]

This information can be retrieved in the response headers:

 connection: keep-alive
 content-length: 18
 content-type: text/html; charset=utf-8
 date: Wed, 16 May 2018 07:32:23 GMT
 errors: [{"keyword": "minLength","dataPath": ".password", "schemaPath": "#/properties/password/minLength", "params": {"limit": 6}, "message": "should NOT be shorter than 6 characters", "modelName": "User"}]
 etag: W/"12-Bpa0T7/lBA6+IACzRWwBc4S6NUY"
 vary: Accept-Encoding
 x-powered-by: Express