gody
gody copied to clipboard
Set rule from dynamic values
Nowadays there's only support to static configuration. For example, configuring some rule to Enum validation it's necessary set this Enum value statically.
I had on problem using defined const values in my source code in validation rule, follow the code example below:
...
type Status string
const (
StatusCreated Status = "__CREATED__"
StatusPending Status = "__PENDING__"
StatusDoing Status = "__DOING__"
StatusDone Status = "__DONE__"
)
...
type Task struct {
Name string
Status Status `json:"status" validate:"enum=__CREATED__,__PENDING__,__DOING__,__DONE__"`
}
...
validator := gody.NewValidator()
validator.AddRules(rule.Enum)
task := Task{}
validator.Validate(task)
With the previous example we have a problem of duplicity and my suggestion for the static config problem is likely this source code below:
type Status string
const (
StatusCreated Status = "__CREATED__"
StatusPending Status = "__PENDING__"
StatusDoing Status = "__DOING__"
StatusDone Status = "__DONE__"
)
...
type Task struct {
Name string
Status Status `json:"status" validate:"enum={status}"`
}
...
validator := gody.NewValidator()
validator.AddRuleParameters(...[]rule.Parameter{
{
Name: "status",
Value: fmt.Sprintf("%s,%s,%s,%s", StatusCreated, StatusPending, StatusDoing, StatusDone),
},
})
validator.AddRules(rule.Enum)
task := Task{}
validator.Validate(task)