Files
validate/length.go
T

58 lines
1.7 KiB
Go
Raw Normal View History

package validate
2026-09-07 16:27:22 +01:00
import "unicode/utf8"
2023-10-07 13:42:17 +01:00
var (
2026-09-07 16:48:29 +01:00
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")
)
2026-09-07 13:59:59 +01:00
// MaxLength validates that a string is no longer than a given maximum.
2026-09-07 16:27:22 +01:00
// Length is counted in runes, so multi-byte characters count as one.
func MaxLength(l int) func(string) error {
return func(value string) error {
2026-09-07 16:27:22 +01:00
if utf8.RuneCountInString(value) > l {
2023-11-19 20:42:48 +00:00
return ErrMustBeShorter.With(l)
}
return nil
}
}
2026-09-07 13:59:59 +01:00
// MinLength validates that a string is at least a given minimum length.
2026-09-07 16:27:22 +01:00
// Length is counted in runes, so multi-byte characters count as one.
func MinLength(l int) func(string) error {
return func(value string) error {
2026-09-07 16:27:22 +01:00
if utf8.RuneCountInString(value) < l {
2023-11-19 20:42:48 +00:00
return ErrMustBeLonger.With(l)
}
return nil
}
}
2026-09-07 16:48:29 +01:00
// 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
}
}