Skip to content

Commit

Permalink
Merge pull request go-playground#541 from JonathanWThom/jt/space-sepa…
Browse files Browse the repository at this point in the history
…rated-oneof

Adds ability to validate oneof for space separated strings
  • Loading branch information
fairyhunter13 committed Dec 24, 2019
2 parents a96f30d + 9a680eb commit 1df836a
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 3 deletions.
5 changes: 4 additions & 1 deletion baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,10 @@ func parseOneOfParam2(s string) []string {
oneofValsCacheRWLock.RUnlock()
if !ok {
oneofValsCacheRWLock.Lock()
vals = strings.Fields(s)
vals = splitParamsRegex.FindAllString(s, -1)
for i := 0; i < len(vals); i++ {
vals[i] = strings.Replace(vals[i], "'", "", -1)
}
oneofValsCache[s] = vals
oneofValsCacheRWLock.Unlock()
}
Expand Down
6 changes: 4 additions & 2 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,10 +361,12 @@ One Of
For strings, ints, and uints, oneof will ensure that the value
is one of the values in the parameter. The parameter should be
a list of values separated by whitespace. Values may be
strings or numbers.
a list of values separated by whitespace. Values may be
strings or numbers. To match strings with spaces in them, include
the target string between single quotes.
Usage: oneof=red green
oneof='red green' 'blue yellow'
oneof=5 7 9
Greater Than
Expand Down
2 changes: 2 additions & 0 deletions regexes.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const (
uRLEncodedRegexString = `(%[A-Fa-f0-9]{2})`
hTMLEncodedRegexString = `&#[x]?([0-9a-fA-F]{2})|(&gt)|(&lt)|(&quot)|(&amp)+[;]?`
hTMLRegexString = `<[/]?([a-zA-Z]+).*?>`
splitParamsRegexString = `'[^']*'|\S+`
)

var (
Expand Down Expand Up @@ -92,4 +93,5 @@ var (
uRLEncodedRegex = regexp.MustCompile(uRLEncodedRegexString)
hTMLEncodedRegex = regexp.MustCompile(hTMLEncodedRegexString)
hTMLRegex = regexp.MustCompile(hTMLRegexString)
splitParamsRegex = regexp.MustCompile(splitParamsRegexString)
)
3 changes: 3 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4487,6 +4487,8 @@ func TestOneOfValidation(t *testing.T) {
}{
{f: "red", t: "oneof=red green"},
{f: "green", t: "oneof=red green"},
{f: "red green", t: "oneof='red green' blue"},
{f: "blue", t: "oneof='red green' blue"},
{f: 5, t: "oneof=5 6"},
{f: 6, t: "oneof=5 6"},
{f: int8(6), t: "oneof=5 6"},
Expand All @@ -4512,6 +4514,7 @@ func TestOneOfValidation(t *testing.T) {
}{
{f: "", t: "oneof=red green"},
{f: "yellow", t: "oneof=red green"},
{f: "green", t: "oneof='red green' blue"},
{f: 5, t: "oneof=red green"},
{f: 6, t: "oneof=red green"},
{f: 6, t: "oneof=7"},
Expand Down

0 comments on commit 1df836a

Please sign in to comment.