Merge f8e597abf5c0f4dd81267541eca7f34eb2b4ff58 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
stareezy 2026-10-13 02:05:53 -07:00 committed by GitHub
commit 7d5638237e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 37 additions and 1 deletions

View File

@ -16,6 +16,15 @@ import (
type defaultValidator struct {
once sync.Once
validate *validator.Validate
options []validator.Option
}
// NewStructValidator returns Gin's default StructValidator configured with
// options passed to validator.New.
func NewStructValidator(options ...validator.Option) StructValidator {
return &defaultValidator{
options: append([]validator.Option(nil), options...),
}
}
type SliceValidationError []error
@ -92,7 +101,7 @@ func (v *defaultValidator) Engine() any {
func (v *defaultValidator) lazyinit() {
v.once.Do(func() {
v.validate = validator.New()
v.validate = validator.New(v.options...)
v.validate.SetTagName("binding")
})
}

View File

@ -7,6 +7,8 @@ package binding
import (
"errors"
"testing"
"github.com/go-playground/validator/v10"
)
func TestSliceValidationError(t *testing.T) {
@ -88,3 +90,20 @@ func TestDefaultValidator(t *testing.T) {
})
}
}
func TestNewStructValidatorWithOptions(t *testing.T) {
type customID struct {
value string
}
type createRequest struct {
ID customID `binding:"required"`
}
v := NewStructValidator(validator.WithRequiredStructEnabled())
if err := v.ValidateStruct(createRequest{}); err == nil {
t.Fatal("expected required validation to reject a zero-value struct")
}
if err := v.ValidateStruct(createRequest{ID: customID{value: "present"}}); err != nil {
t.Fatalf("expected non-zero struct to pass validation: %v", err)
}
}

View File

@ -973,6 +973,14 @@ Skip-validation: Running the example above using the `curl` command returns an e
It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).
Constructor-only validator options can be applied by replacing `binding.Validator` before handling requests:
```go
binding.Validator = binding.NewStructValidator(
validator.WithRequiredStructEnabled(),
)
```
```go
package main