Skip to content

Commit

Permalink
fix: length validation for utf8 strings
Browse files Browse the repository at this point in the history
  • Loading branch information
maximdanilchenko committed Mar 12, 2024
1 parent 13acb69 commit 763b669
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
5 changes: 3 additions & 2 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"
"unsafe"
)

Expand Down Expand Up @@ -412,12 +413,12 @@ func Validate(r Registry, s *Schema, path *PathBuffer, mode ValidateMode, v any,
}

if s.MinLength != nil {
if len(str) < *s.MinLength {
if utf8.RuneCountInString(str) < *s.MinLength {
res.Addf(path, str, s.msgMinLength)
}
}
if s.MaxLength != nil {
if len(str) > *s.MaxLength {
if utf8.RuneCountInString(str) > *s.MaxLength {
res.Add(path, str, s.msgMaxLength)
}
}
Expand Down
7 changes: 7 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,13 @@ var validateTests = []struct {
}{}),
input: map[string]any{"value": "a"},
},
{
name: "non ascii max length success",
typ: reflect.TypeOf(struct {
Value string `json:"value" maxLength:"2"`
}{}),
input: map[string]any{"value": "аб"},
},
{
name: "max length fail",
typ: reflect.TypeOf(struct {
Expand Down

0 comments on commit 763b669

Please sign in to comment.