Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Commit

Permalink
Length counter fixed for emoji like multi byte characters (#152)
Browse files Browse the repository at this point in the history
* Length counter fixed for emoji like multi byte characters

* Length counter fix tests are added for emoji containing strings
  • Loading branch information
ozguncagri authored and AlecAivazis committed Oct 25, 2018
1 parent f30c5d1 commit 0be4439
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
4 changes: 2 additions & 2 deletions validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func MaxLength(length int) Validator {
return func(val interface{}) error {
if str, ok := val.(string); ok {
// if the string is longer than the given value
if len(str) > length {
if len([]rune(str)) > length {
// yell loudly
return fmt.Errorf("value is too long. Max length is %v", length)
}
Expand All @@ -44,7 +44,7 @@ func MinLength(length int) Validator {
return func(val interface{}) error {
if str, ok := val.(string); ok {
// if the string is shorter than the given value
if len(str) < length {
if len([]rune(str)) < length {
// yell loudly
return fmt.Errorf("value is too short. Min length is %v", length)
}
Expand Down
14 changes: 14 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,27 @@ func TestMaxLength(t *testing.T) {
if err := MaxLength(140)(testStr); err == nil {
t.Error("No error returned with input greater than 150 characters.")
}

// emoji test
emojiStr := "I😍Golang"
// validate visible length with Maxlength
if err := MaxLength(10)(emojiStr); err != nil {
t.Errorf("Error returned with emoji containing 8 characters long input.")
}
}

func TestMinLength(t *testing.T) {
// validate the string
if err := MinLength(12)(randString(10)); err == nil {
t.Error("No error returned with input less than 12 characters.")
}

// emoji test
emojiStr := "I😍Golang"
// validate visibly 8 characters long string with MinLength
if err := MinLength(10)(emojiStr); err == nil {
t.Error("No error returned with emoji containing input less than 10 characters.")
}
}

func TestMinLength_onInt(t *testing.T) {
Expand Down

0 comments on commit 0be4439

Please sign in to comment.