Skip to content

Commit

Permalink
fix: use rune for length checking
Browse files Browse the repository at this point in the history
  • Loading branch information
AgentCosmic committed Jun 29, 2023
1 parent acbb273 commit c587765
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
4 changes: 2 additions & 2 deletions validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func (c *MinStrValidator) Validate(value interface{}) Error {
if c.optional && str == "" {
return nil
}
if len(str) < int(c.min) {
if len([]rune(str)) < int(c.min) {
return createError(c.name, c.message, fmt.Sprintf("Please lengthen %s to %d characters or more", c.name, c.min))
}
return nil
Expand Down Expand Up @@ -165,7 +165,7 @@ func (c *MaxStrValidator) SetMessage(msg string) Validator {

// Validate the value
func (c *MaxStrValidator) Validate(value interface{}) Error {
if len(value.(string)) > int(c.max) {
if len([]rune(value.(string))) > int(c.max) {
return createError(c.name, c.message, fmt.Sprintf("Please shorten %s to %d characters or less", c.name, c.max))
}
return nil
Expand Down
2 changes: 2 additions & 0 deletions xvalid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func TestMinStr(t *testing.T) {
assert.Nil(t, rules.Validate(strType{Field: "123"}), "Long enough")
assert.Nil(t, rules.Validate(strType{Field: "12"}), "Exactly hit min")
assert.Len(t, rules.Validate(strType{Field: "1"}).(Errors), 1, "Too short")
assert.Len(t, rules.Validate(strType{Field: "£"}).(Errors), 1, "Multi-byte characters too short")
msg := "custom message"
assert.Equal(t, msg, New(&str).Field(&str.Field, MinStr(2).SetMessage(msg)).
Validate(strType{Field: "1"}).(Errors)[0].Error(), "Custom error message")
Expand All @@ -93,6 +94,7 @@ func TestMaxStr(t *testing.T) {
assert.Len(t, rules.Validate(strType{Field: "123"}).(Errors), 1, "Short enough")
assert.Nil(t, rules.Validate(strType{Field: "12"}), "Exactly hit max")
assert.Nil(t, rules.Validate(strType{Field: "1"}), "Short enough")
assert.Nil(t, rules.Validate(strType{Field: "世界"}), "Multi-byte characters are short enough")
msg := "custom message"
assert.Equal(t, msg, New(&str).Field(&str.Field, MaxStr(0).SetMessage(msg)).
Validate(strType{Field: "1"}).(Errors)[0].Error(), "Custom error message")
Expand Down

0 comments on commit c587765

Please sign in to comment.