Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
2 tasks done
christeredvartsen opened this issue Aug 19, 2024 · 1 comment
Open
2 tasks done

Comments

@christeredvartsen
Copy link

  • I have looked at the documentation here first?
  • I have looked at the examples provided that may showcase my question here?

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant