Skip to content

Set rule from dynamic values #12

Open
@guiferpa

Description

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)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions