From c48de9bc8d1e7d15de51dde2ba3b96ab4d4ffaf8 Mon Sep 17 00:00:00 2001 From: feofanov Date: Sat, 11 Apr 2020 14:02:24 +0500 Subject: [PATCH] fix validation with empty request body --- validator.go | 2 +- validator_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/validator.go b/validator.go index c88e74c..8096c9d 100644 --- a/validator.go +++ b/validator.go @@ -170,7 +170,7 @@ func (v *Validator) ValidateStruct() url.Values { func (v *Validator) internalValidateStruct() url.Values { errsBag := url.Values{} - if v.Opts.Request != nil { + if v.Opts.Request != nil && v.Opts.Request.Body != http.NoBody { defer v.Opts.Request.Body.Close() err := json.NewDecoder(v.Opts.Request.Body).Decode(v.Opts.Data) if err != nil { diff --git a/validator_test.go b/validator_test.go index ab9896e..cc67005 100644 --- a/validator_test.go +++ b/validator_test.go @@ -170,6 +170,38 @@ func TestValidator_ValidateJSON_NULLValue(t *testing.T) { } } +func TestValidator_ValidateJSON_NoBody(t *testing.T) { + type User struct { + Name string `json:"name"` + Count Int `json:"count"` + Option Int `json:"option"` + Active Bool `json:"active"` + } + + rules := MapData{ + "name": []string{"required"}, + "count": []string{"required"}, + "option": []string{"required"}, + "active": []string{"required"}, + } + + var user User + req, _ := http.NewRequest("POST", "http://www.example.com", bytes.NewReader(nil)) + + opts := Options{ + Request: req, + Data: &user, + Rules: rules, + } + + vd := New(opts) + vd.SetTagIdentifier("json") + validationErr := vd.ValidateJSON() + if len(validationErr) != len(rules) { + t.Error("ValidateJSON with empty request body failed") + } +} + func TestValidator_ValidateStruct(t *testing.T) { type User struct { Name string `json:"name"`