yuta
yuta

Reputation: 19

Can I conditional validate from parent struct value ? (https://github.com/go-playground/validator)

I'm trying to validate using https://github.com/go-playground/validator.

I'm facing problem that conditional validation depend on parent struct value.

First of all that validation can be done ? If can not be, could you give me a hint that solve these problems.

Thanks.

type A struct {
  Enabled bool `json:"enabled" validate:"required"`
  Reason  struct {
        Note     string `json:"note" validate:"required_if=Enabled true"` // if parent's Enabled is true that struct will be required 
  } `json:"reason" validate:"required"`
}

Upvotes: 0

Views: 450

Answers (1)

Huỳnh Hải Nam
Huỳnh Hải Nam

Reputation: 11

Just define Reason as pointer so it will be fine.

type A struct {
  Enabled bool `json:"enabled" validate:"required"`
  Reason  *Reason `json:"reason" validate:"required_if=Enabled true"`
}

type Reason struct {
        Note     string `json:"note" validate:"required"` 
} 

Another way: u can custom the validate https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions

Upvotes: 1

Related Questions