Custom validation
You can add runtime validation for your user input for Prisma Client queries in one of the following ways:
- Prisma Client extensions
- A custom function
You can use any validation library you'd like. The Node.js ecosystem offers a number of high-quality, easy-to-use validation libraries to choose from including: joi, validator.js, Yup, Zod and Superstruct.
Input validation with Prisma Client extensions
Prisma Client extensions are currently in Preview.
This example adds runtime validation when creating and updating values using a Zod schema to check that the data passed to Prisma Client is valid.
Query extensions do not currently work for nested operations. In this example, validations are only run on the top level data object passed to methods such as prisma.product.create()
. Validations implemented this way do not automatically run for nested writes.
The above example uses a Zod schema to validate and parse data provided in a query at runtime before a record is written to the database.
Input validation with a custom validation function
Here's an example using Superstruct to validate that the data needed to signup a new user is correct:
import { PrismaClient, Prisma, User } from '@prisma/client'import { assert, object, string, size, refine } from 'superstruct'import isEmail from 'isemail'const prisma = new PrismaClient()// Runtime validationconst Signup = object({// string and a valid email addressemail: refine(string(), 'email', (v) => isEmail.validate(v)),// password is between 7 and 30 characters longpassword: size(string(), 7, 30),// first name is between 2 and 50 characters longfirstName: size(string(), 2, 50),// last name is between 2 and 50 characters longlastName: size(string(), 2, 50),})type Signup = Omit<Prisma.UserCreateArgs['data'], 'id'>// Signup functionasync function signup(input: Signup): Promise<User> {// Assert that input conforms to Signup, throwing with a helpful// error message if input is invalid.assert(input, Signup)return prisma.user.create({data: input.user,})}
The example above shows how you can create a custom type-safe signup
function that ensures the input is valid before creating a user.
Going further
- Learn how you can use Prisma Client extensions to add input validation for your queries — example.
- Learn how you can organize your code better by moving the
signup
function into a custom model. - There's an outstanding feature request to bake user validation into Prisma Client. If you'd like to see that happen, make sure to upvote that issue and share your use case!