Skip to content

Commit

Permalink
Add indexes not unique array items to error details
Browse files Browse the repository at this point in the history
  • Loading branch information
austinov committed Nov 8, 2018
1 parent f3a9dae commit ae0d993
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 5 deletions.
2 changes: 1 addition & 1 deletion errors.go
Expand Up @@ -81,7 +81,7 @@ type (
ResultErrorFields
}

// ItemsMustBeUniqueError. ErrorDetails: type
// ItemsMustBeUniqueError. ErrorDetails: type, i, j
ItemsMustBeUniqueError struct {
ResultErrorFields
}
Expand Down
2 changes: 1 addition & 1 deletion locales.go
Expand Up @@ -147,7 +147,7 @@ func (l DefaultLocale) ArrayMaxItems() string {
}

func (l DefaultLocale) Unique() string {
return `{{.type}} items must be unique`
return `{{.type}} items[{{.i}},{{.j}}] must be unique`
}

func (l DefaultLocale) ArrayContains() string {
Expand Down
10 changes: 10 additions & 0 deletions utils.go
Expand Up @@ -62,6 +62,16 @@ func isStringInSlice(s []string, what string) bool {
return false
}

// indexStringInSlice returns the index of the first instance of 'what' in s or -1 if it is not found in s.
func indexStringInSlice(s []string, what string) int {
for i := range s {
if s[i] == what {
return i
}
}
return -1
}

func marshalToJsonString(value interface{}) (*string, error) {

mBytes, err := json.Marshal(value)
Expand Down
6 changes: 3 additions & 3 deletions validation.go
Expand Up @@ -517,17 +517,17 @@ func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface
// uniqueItems:
if currentSubSchema.uniqueItems {
var stringifiedItems []string
for _, v := range value {
for j, v := range value {
vString, err := marshalWithoutNumber(v)
if err != nil {
result.addInternalError(new(InternalError), context, value, ErrorDetails{"err": err})
}
if isStringInSlice(stringifiedItems, *vString) {
if i := indexStringInSlice(stringifiedItems, *vString); i > -1 {
result.addInternalError(
new(ItemsMustBeUniqueError),
context,
value,
ErrorDetails{"type": TYPE_ARRAY},
ErrorDetails{"type": TYPE_ARRAY, "i": i, "j": j},
)
}
stringifiedItems = append(stringifiedItems, *vString)
Expand Down

0 comments on commit ae0d993

Please sign in to comment.