Broadens the built-in set with the string/presence checks that came up most often when reaching for this package: - Required[T comparable] non-zero value - Prefix / Suffix / Contains strings.HasPrefix/HasSuffix/Contains - Match(*regexp.Regexp) arbitrary pattern All follow the existing shape: a constructor returning func(T) error, a sentinel error matched with errors.Is, table-driven tests and an Example. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
42 lines
957 B
Go
42 lines
957 B
Go
package validate
|
|
|
|
import (
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
ErrMissingPrefix = NewError("must start with %q")
|
|
ErrMissingSuffix = NewError("must end with %q")
|
|
ErrMissingSubstring = NewError("must contain %q")
|
|
)
|
|
|
|
// Prefix validates that a string begins with a given prefix.
|
|
func Prefix(prefix string) func(string) error {
|
|
return func(value string) error {
|
|
if !strings.HasPrefix(value, prefix) {
|
|
return ErrMissingPrefix.With(prefix)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// Suffix validates that a string ends with a given suffix.
|
|
func Suffix(suffix string) func(string) error {
|
|
return func(value string) error {
|
|
if !strings.HasSuffix(value, suffix) {
|
|
return ErrMissingSuffix.With(suffix)
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// Contains validates that a string contains a given substring.
|
|
func Contains(substr string) func(string) error {
|
|
return func(value string) error {
|
|
if !strings.Contains(value, substr) {
|
|
return ErrMissingSubstring.With(substr)
|
|
}
|
|
return nil
|
|
}
|
|
}
|