Class Validator
Validate body, Based on class-validator.
for complete doc, please visit class-validator.
Install
install external libs @nhttp/class-validator
.
- Deno
- deno.land
- npm
- Bun
- Yarn
- pnpm
deno add @nhttp/class-validator
import {...} from "https://deno.land/x/nhttp/lib/class-validator.ts";
npx jsr add @nhttp/class-validator
bunx jsr add @nhttp/class-validator
yarn dlx jsr add @nhttp/class-validator
pnpm dlx jsr 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": [...]
}