Add runtime validation to models
See original GitHub issueProblem
Before saving data to the database, it’s common to perform validation.
When using Prisma to save user data (in an API), Prisma will perform runtime validation before saving to the database and throw an error if the user data doesn’t match the type.
Even with TypeScript, these checks cannot happen at compile time because the user data is not known.
Since there are situations where you want to validate the data as a separate step to saving to the database, it’d be nice if Prisma exposed the same validation functionality as a standalone method on models.
Suggested solution
Provide a validate function for models which is based on the Prisma schema:
model User {
id Int @default(autoincrement()) @id
email String @unique
firstName String?
lastName String?
social Json?
isAdmin Boolean @default(false)
}
API ideas:
const { isValid, error } = prisma.user.validate(user)
The idea is that If the input is valid, then the error will be undefined. If the input is invalid, error
is assigned an Error object providing more information.
OR
const user = { firstName: 'Laura' }
try {
const validatedUser = await prisma.user.validate(user)
} catch (error) {
// handle error
}
Additional context
For inspiration, Joi’s validation errors might be useful (albeit more extensive as Joi has richer validation rules).
Issue Analytics
- State:
- Created 3 years ago
- Reactions:245
- Comments:36 (4 by maintainers)
The ideas presented in #3102 seems really good, like:
Then being used like this:
An implicit conversion, say, a numeric string to a number (like mongoose does) would also be nice to prevent from manually having to cast the values or being too strict about types that JS considers “interchangeable” in some cases
so… until that happens… what is the best way to do model validation today with prisma 2 ?