length: add MinLengthBytes / MaxLengthBytes
CI / test (pull_request) Successful in 34s
CI / test (push) Successful in 37s

MinLength/MaxLength now count runes, leaving no way to bound a string by
its byte size -- still wanted for fixed-width columns and wire-format
fields. Add the byte-counting pair alongside them, with their own "%d
bytes" sentinels (ErrMustHaveMoreBytes / ErrMustHaveFewerBytes).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit was merged in pull request #11.
This commit is contained in:
2026-09-07 16:48:29 +01:00
co-authored by Claude Sonnet 5
parent 4e2e05c1b9
commit 164dcbf367
3 changed files with 96 additions and 3 deletions
+29 -2
View File
@@ -3,8 +3,10 @@ package validate
import "unicode/utf8"
var (
ErrMustBeLonger = NewError("must contain at least %d characters")
ErrMustBeShorter = NewError("must contain no more than %d characters")
ErrMustBeLonger = NewError("must contain at least %d characters")
ErrMustBeShorter = NewError("must contain no more than %d characters")
ErrMustHaveMoreBytes = NewError("must have at least %d bytes")
ErrMustHaveFewerBytes = NewError("must have no more than %d bytes")
)
// MaxLength validates that a string is no longer than a given maximum.
@@ -28,3 +30,28 @@ func MinLength(l int) func(string) error {
return nil
}
}
// MaxLengthBytes validates that a string is no longer than a given maximum
// number of bytes (len). Prefer [MaxLength] for a limit on visible
// characters; use this when the budget is genuinely a byte count, such as
// a fixed-width column or a wire-format field.
func MaxLengthBytes(l int) func(string) error {
return func(value string) error {
if len(value) > l {
return ErrMustHaveFewerBytes.With(l)
}
return nil
}
}
// MinLengthBytes validates that a string is at least a given minimum
// number of bytes (len). See [MaxLengthBytes] on when to prefer this over
// [MinLength].
func MinLengthBytes(l int) func(string) error {
return func(value string) error {
if len(value) < l {
return ErrMustHaveMoreBytes.With(l)
}
return nil
}
}