Files
validate/length.go
T
claudeandClaude Sonnet 5 164dcbf367
CI / test (pull_request) Successful in 34s
CI / test (push) Successful in 37s
length: add MinLengthBytes / MaxLengthBytes
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>
2026-09-07 16:48:29 +01:00

58 lines
1.7 KiB
Go

package validate
import "unicode/utf8"
var (
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.
// 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
}
}
// 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
}
}