diff --git a/baked_in.go b/baked_in.go index 8e6b169cb..82162e99b 100644 --- a/baked_in.go +++ b/baked_in.go @@ -2568,9 +2568,17 @@ func isDirPath(fl FieldLevel) bool { func isJSON(fl FieldLevel) bool { field := fl.Field() - if field.Kind() == reflect.String { + switch field.Kind() { + case reflect.String: val := field.String() return json.Valid([]byte(val)) + case reflect.Slice: + fieldType := field.Type() + + if fieldType.ConvertibleTo(byteSliceType) { + b := field.Convert(byteSliceType).Interface().([]byte) + return json.Valid(b) + } } panic(fmt.Sprintf("Bad field type %T", field.Interface())) diff --git a/validator_instance.go b/validator_instance.go index d2ee8fe38..d9dbf0ce8 100644 --- a/validator_instance.go +++ b/validator_instance.go @@ -53,6 +53,8 @@ var ( timeDurationType = reflect.TypeOf(time.Duration(0)) timeType = reflect.TypeOf(time.Time{}) + byteSliceType = reflect.TypeOf([]byte{}) + defaultCField = &cField{namesEqual: true} ) diff --git a/validator_test.go b/validator_test.go index a60e4bce1..9fbc41c8d 100644 --- a/validator_test.go +++ b/validator_test.go @@ -11958,7 +11958,7 @@ func TestGetTag(t *testing.T) { func TestJSONValidation(t *testing.T) { tests := []struct { - param string + param interface{} expected bool }{ {`foo`, false}, @@ -11975,6 +11975,34 @@ func TestJSONValidation(t *testing.T) { {`true`, true}, {`null`, true}, {`"null"`, true}, + {json.RawMessage(`foo`), false}, + {json.RawMessage(`}{`), false}, + {json.RawMessage(`{]`), false}, + {json.RawMessage(`{}`), true}, + {json.RawMessage(`{"foo":"bar"}`), true}, + {json.RawMessage(`{"foo":"bar","bar":{"baz":["qux"]}}`), true}, + {json.RawMessage(`{"foo": 3 "bar": 4}`), false}, + {json.RawMessage(`{"foo": 3 ,"bar": 4`), false}, + {json.RawMessage(`{foo": 3, "bar": 4}`), false}, + {json.RawMessage(`foo`), false}, + {json.RawMessage(`1`), true}, + {json.RawMessage(`true`), true}, + {json.RawMessage(`null`), true}, + {json.RawMessage(`"null"`), true}, + {[]byte(`foo`), false}, + {[]byte(`}{`), false}, + {[]byte(`{]`), false}, + {[]byte(`{}`), true}, + {[]byte(`{"foo":"bar"}`), true}, + {[]byte(`{"foo":"bar","bar":{"baz":["qux"]}}`), true}, + {[]byte(`{"foo": 3 "bar": 4}`), false}, + {[]byte(`{"foo": 3 ,"bar": 4`), false}, + {[]byte(`{foo": 3, "bar": 4}`), false}, + {[]byte(`foo`), false}, + {[]byte(`1`), true}, + {[]byte(`true`), true}, + {[]byte(`null`), true}, + {[]byte(`"null"`), true}, } validate := New()