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>
This commit was merged in pull request #11.
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user