Skip to content

Keep validator in sync with DB enums #1449

Answered by deankarn
MarkForLoop asked this question in Q&A
Discussion options

You must be logged in to vote

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)

}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by MarkForLoop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants