Skip to content

Commit

Permalink
fix validation with empty request body
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan-Feofanov committed Apr 11, 2020
1 parent a8b0eb4 commit c48de9b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion validator.go
Expand Up @@ -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 {
Expand Down
32 changes: 32 additions & 0 deletions validator_test.go
Expand Up @@ -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"`
Expand Down

0 comments on commit c48de9b

Please sign in to comment.