add Required, Prefix, Suffix, Contains, Match validators
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>
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func ExampleMatch() {
|
||||
slug := Match(regexp.MustCompile(`^[a-z0-9-]+$`))
|
||||
fmt.Println(slug("Not A Slug"))
|
||||
// Output: invalid format
|
||||
}
|
||||
|
||||
func TestMatch(t *testing.T) {
|
||||
v := Match(regexp.MustCompile(`^[a-z0-9-]+$`))
|
||||
|
||||
testCases := map[string]error{
|
||||
"hello-world-123": nil,
|
||||
"abc": nil,
|
||||
|
||||
"Hello": ErrNoMatch,
|
||||
"has space": ErrNoMatch,
|
||||
"": ErrNoMatch,
|
||||
}
|
||||
|
||||
for input, want := range testCases {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
if got := v(input); !errors.Is(got, want) {
|
||||
t.Error("got", got, "want", want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user