Keep validator in sync with DB enums #1449
-
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? |
Beta Was this translation helpful? Give feedback.
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)
} |
Beta Was this translation helpful? Give feedback.
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: