mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-22 02:43:36 +08:00
feat(binding): support validator options
This commit is contained in:
parent
34dac209ff
commit
f8e597abf5
@ -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")
|
||||
})
|
||||
}
|
||||
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -932,6 +932,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
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user