Skip to content

Commit 460c834

Browse files
authored
Merge pull request go-validator#52 from Fank/v2
Escape tag contents comma
2 parents 07ffaad + 48da120 commit 460c834

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

validator.go

+18-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"errors"
2121
"fmt"
2222
"reflect"
23+
"regexp"
2324
"strings"
2425
"unicode"
2526
)
@@ -327,11 +328,27 @@ type tag struct {
327328
Param string // parameter to send to the validation function
328329
}
329330

331+
// separate by no escaped commas
332+
var sepPattern *regexp.Regexp = regexp.MustCompile(`((?:^|[^\\])(?:\\\\)*),`)
333+
334+
func splitUnescapedComma(str string) []string {
335+
ret := []string{}
336+
indexes := sepPattern.FindAllStringIndex(str, -1)
337+
last := 0
338+
for _, is := range indexes {
339+
ret = append(ret, str[last:is[1]-1])
340+
last = is[1]
341+
}
342+
ret = append(ret, str[last:])
343+
return ret
344+
}
345+
330346
// parseTags parses all individual tags found within a struct tag.
331347
func (mv *Validator) parseTags(t string) ([]tag, error) {
332-
tl := strings.Split(t, ",")
348+
tl := splitUnescapedComma(t)
333349
tags := make([]tag, 0, len(tl))
334350
for _, i := range tl {
351+
i = strings.Replace(i, `\,`, ",", -1)
335352
tg := tag{}
336353
v := strings.SplitN(i, "=", 2)
337354
tg.Name = strings.Trim(v[0], " ")

validator_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,22 @@ func (ms *MySuite) TestCopy(c *C) {
467467
c.Assert(errs["A"], HasError, validator.ErrUnknownTag)
468468
}
469469

470+
func (ms *MySuite) TestTagEscape(c *C) {
471+
type test struct {
472+
A string `validate:"min=0,regexp=^a{3\\,10}"`
473+
}
474+
t := test{"aaaa"}
475+
err := validator.Validate(t)
476+
c.Assert(err, IsNil)
477+
478+
t2 := test{"aa"}
479+
err = validator.Validate(t2)
480+
c.Assert(err, NotNil)
481+
errs, ok := err.(validator.ErrorMap)
482+
c.Assert(ok, Equals, true)
483+
c.Assert(errs["A"], HasError, validator.ErrRegexp)
484+
}
485+
470486
type hasErrorChecker struct {
471487
*CheckerInfo
472488
}

0 commit comments

Comments
 (0)