Prisma Class Validator Generator
The `prisma-class-validator-generator` is a utility that automates the creation of TypeScript data transfer objects (DTOs) directly from a Prisma schema, automatically decorating them with `class-validator` rules. This eliminates significant boilerplate for developers working with Prisma and `class-validator` for input validation. The package is currently stable at version `6.2.0`, following a relatively active release cadence with semantic versioning adopted since v6.1.0, indicating consistent development and maintenance. Key differentiators include its tight integration with Prisma, providing automatic mapping of Prisma types to appropriate validation decorators, ensuring type-safety, and offering a zero-configuration setup for immediate use. It supports modern Prisma versions, currently `Prisma 6.12+`, and is designed for Node.js 18+ environments with TypeScript 5.8+. This generator is crucial for projects aiming for robust backend validation without manually synchronizing schema changes with validation classes.
Common errors
-
Error: Generator 'class_validator' could not be found.
cause The `prisma-class-validator-generator` package is not installed or not accessible in the project's node_modules.fixRun `npm install prisma-class-validator-generator` or `yarn add prisma-class-validator-generator` in your project. -
Cannot find module './generated/models' or './generated/models/User'
cause The generated files do not exist or the import path is incorrect. This usually happens if `npx prisma generate` hasn't been run, or if the `output` path in `schema.prisma` differs from the import statement.fixEnsure you've run `npx prisma generate` successfully. Verify the `output` path in your `schema.prisma` generator configuration matches your import path, and check if the files were indeed created at the specified location. -
Validation fails unexpectedly for incoming JSON objects, even with seemingly correct data.
cause `class-validator` requires class instances to apply validation decorators. If you're passing plain JavaScript objects (e.g., from an API request body) directly to `validate()`, the decorators won't be applied.fixUse `class-transformer`'s `plainToClass` function to convert your plain object into an instance of the generated class before calling `validate()`. Example: `const instance = plainToClass(MyGeneratedClass, plainObject); await validate(instance);`
Warnings
- breaking Version 6.0.0 introduced a breaking change for `Bytes` fields, now supporting `Uint8Array` instead of `Buffer`. Projects using `Bytes` types in Prisma schemas will need to update their handling of these fields accordingly.
- breaking Version 5.0.0 primarily upgraded support to Prisma 5.x. Users on older Prisma versions (4.x or earlier) should expect breaking changes and are required to upgrade their Prisma client and schema to be compatible.
- gotcha The generator requires a `prisma-client` or `prisma-client-js` generator to be present and configured in the same `schema.prisma` file for proper type inference and functionality. Without it, the generator may fail or produce incorrect output.
- gotcha Version 6.x requires Node.js 18+ and TypeScript 5.8+. Using older versions may lead to build errors or runtime incompatibilities.
Install
-
npm install prisma-class-validator-generator -
yarn add prisma-class-validator-generator -
pnpm add prisma-class-validator-generator
Imports
- User
const User = require('./generated/models');import { User } from './generated/models'; - validate
const validate = require('class-validator').validate;import { validate } from 'class-validator'; - plainToClass
import { plainToClass } from 'class-validator';import { plainToClass } from 'class-transformer';
Quickstart
/* schema.prisma */
generator client {
provider = "prisma-client"
output = "../generated/prisma-client"
}
generator class_validator {
provider = "prisma-class-validator-generator"
output = "./generated"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
viewCount Int @default(0)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
rating Float
}
/* Usage in TypeScript file */
import { User } from './generated/models';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
async function validateUser(userData: any) {
const userInstance = plainToClass(User, userData);
const errors = await validate(userInstance);
if (errors.length > 0) {
console.error('Validation failed:', errors);
return false;
} else {
console.log('Validation successful!');
return true;
}
}
// Example usage:
validateUser({ email: 'test@example.com', name: 'John Doe' });
validateUser({ email: 'invalid-email', name: 123 }); // This should fail
// To run this, first ensure `prisma generate` has been executed:
// npx prisma generate