go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.56k stars 1.31k forks source link

Question: How to get omitnil / omitempty and require to work together #1308

Open christeredvartsen opened 1 month ago

christeredvartsen commented 1 month ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

Question

Code sample, to showcase or reproduce:

I have a struct that represents an update / patch, where the fields are pointers, and are only used when the fields are not nil. When using the required rule together with omitnil or omitempty it seems to accept blank values (at least for strings, have not tried with other types yet).

Is there a way to achieve the usage of required only when the pointer is not nil?

package main

import (
    "fmt"
    "github.com/go-playground/validator/v10"
)

type Update struct {
    Field1 *string `validate:"omitnil,required"`
    Field2 *string `validate:"omitempty,required"`
    Field3 *string `validate:"required"`
}

func p(s string) *string {
    return &s
}

func main() {
    validate := validator.New(validator.WithRequiredStructEnabled())
    update := Update{
        Field1: p(""),
        Field2: p(""),
        Field3: p(""),
    }
    if err := validate.Struct(update); err != nil {
        fmt.Printf("%+v\n", err.(validator.ValidationErrors))
    } else {
        fmt.Println("no errors")
    }
}
christeredvartsen commented 1 month ago

We have solved this using omitnil,min=1 combination btw, for those interested in an possible solution.