Skip to content

Commit

Permalink
Support validation constraint "Pattern" for map keys. (#158)
Browse files Browse the repository at this point in the history
Some swaggers define regex constraints for items that go in maps, for
example the keys for "x-ms-meta-" key/value pairs.
  • Loading branch information
jhendrixMSFT authored Aug 14, 2017
1 parent 0545944 commit 48a8154
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
11 changes: 11 additions & 0 deletions autorest/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,17 @@ func validateArrayMap(x reflect.Value, v Constraint) error {
if x.Len() != 0 {
return createError(x, v, "readonly parameter; must send as nil or empty in request")
}
case Pattern:
reg, err := regexp.Compile(v.Rule.(string))
if err != nil {
return createError(x, v, err.Error())
}
keys := x.MapKeys()
for _, k := range keys {
if !reg.MatchString(k.String()) {
return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.Rule))
}
}
default:
return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.Name))
}
Expand Down
2 changes: 2 additions & 0 deletions autorest/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1794,6 +1794,7 @@ func TestValidate_MapValidationWithoutError(t *testing.T) {
{"M", Empty, false, nil},
{"M", MinItems, 1, nil},
{"M", UniqueItems, true, nil},
{"M", Pattern, "^[a-z]+$", nil},
},
},
},
Expand All @@ -1807,6 +1808,7 @@ func TestValidate_MapValidationWithoutError(t *testing.T) {
{"M", Empty, false, nil},
{"M", MinItems, 1, nil},
{"M", UniqueItems, true, nil},
{"M", Pattern, "^[a-z]+$", nil},
},
},
},
Expand Down

0 comments on commit 48a8154

Please sign in to comment.