Keep validator in sync with DB enums #1449
Answered
by
deankarn
MarkForLoop
asked this question in
Q&A
|
I’m really liking this package so far, but I had a quick question, I am moving from TypeScript to Go. In TypeScript, you can pass the generated enum from the DB straight into the validator (like with Zod: https://zod.dev/api#enums) so it stays type-safe. Right now I’m using Is there a way to keep this fully type-safe in Go too? |
Answered by
deankarn
Jul 6, 2025
Replies: 1 comment
|
Hey @MarkForLoop , yes it's possible and I recommend in these cases to register your own validation function for them if you can't use the enum value directly in your structs already. here is a basic example, I'm sure you'd want to abstract it away better in a reusable way. Example: package main
import (
"github.com/go-playground/validator/v10"
)
func main() {
enums := make(map[string]struct{})
db := ...
db.QueryRow("SELECT ENUM values load into enums var ...)...
f:= func(fl validator.FieldLevel) bool {
if _, found := enums[fl.Field().String()]; found {
return true
}
return false
}
v := validator.New()
v.RegisterValidation("myenumfromdb", f)
} |
0 replies
Answer selected by
MarkForLoop
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @MarkForLoop , yes it's possible and I recommend in these cases to register your own validation function for them if you can't use the enum value directly in your structs already.
here is a basic example, I'm sure you'd want to abstract it away better in a reusable way.
Example: