Skip to main content

Class Validator

Validate body, Based on class-validator.

for complete doc, please visit class-validator.

Install

install external libs @nhttp/class-validator.

deno add @nhttp/class-validator

Usage

import {
Controller,
Post,
} from "@nhttp/nhttp/controller";
import {
IsEmail,
IsPhoneNumber,
IsString,
Validate,
} from "@nhttp/class-validator";

// Person Dto
class PersonDto {
@IsString()
name!: string;

@IsEmail()
email!: string;

@IsPhoneNumber()
phone!: string;
}

// Person Controller
@Controller("/person")
class PersonController {

// validate
@Validate(PersonDto)
@Post("/")
save(rev: RequestEvent) {
return rev.body;
}
}

Example Error Message

If not valid, will throw to status 422 (Unprocessable Entity).

{
"status": 422,
"message": [
{
"target": {},
"property": "name",
"children": [],
"constraints": {
"isString": "name must be a string"
}
},
{
"target": {},
"property": "email",
"children": [],
"constraints": {
"isEmail": "email must be an email"
}
},
{
"target": {},
"property": "phone",
"children": [],
"constraints": {
"isPhoneNumber": "phone must be a valid phone number"
}
}
],
"name": "UnprocessableEntityError",
"stack": [...]
}