Files
validate/length.go
T
claudeandClaude Sonnet 5 4e2e05c1b9
CI / test (pull_request) Successful in 34s
length: count runes, not bytes
MinLength/MaxLength measured len(value), so a string of 8 accented
characters (9+ bytes) failed MaxLength(8) despite the error message
promising "characters". Count with utf8.RuneCountInString so the check
matches the wording and the common-sense intent.

Still not grapheme-cluster aware (combining marks, emoji ZWJ sequences
count as several runes), which is out of scope for a stdlib-only helper.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 16:27:22 +01:00

31 lines
827 B
Go

package validate
import "unicode/utf8"
var (
ErrMustBeLonger = NewError("must contain at least %d characters")
ErrMustBeShorter = NewError("must contain no more than %d characters")
)
// MaxLength validates that a string is no longer than a given maximum.
// Length is counted in runes, so multi-byte characters count as one.
func MaxLength(l int) func(string) error {
return func(value string) error {
if utf8.RuneCountInString(value) > l {
return ErrMustBeShorter.With(l)
}
return nil
}
}
// MinLength validates that a string is at least a given minimum length.
// Length is counted in runes, so multi-byte characters count as one.
func MinLength(l int) func(string) error {
return func(value string) error {
if utf8.RuneCountInString(value) < l {
return ErrMustBeLonger.With(l)
}
return nil
}
}