add ExceptChars validator
This commit is contained in:
@@ -20,3 +20,15 @@ func Chars(allow string) func(string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ExceptChars validates whether a string does not contain disallowed characters.
|
||||||
|
func ExceptChars(disallow string) func(string) error {
|
||||||
|
return func(value string) error {
|
||||||
|
for _, r := range disallow {
|
||||||
|
if strings.ContainsRune(value, r) {
|
||||||
|
return ErrDisallowedChars
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ func TestChars(t *testing.T) {
|
|||||||
testCases := []TestCase{
|
testCases := []TestCase{
|
||||||
{Input: "abcd1234", C: hexRange},
|
{Input: "abcd1234", C: hexRange},
|
||||||
{Input: "abcd 1234", C: hexRange, Err: ErrDisallowedChars},
|
{Input: "abcd 1234", C: hexRange, Err: ErrDisallowedChars},
|
||||||
|
{Input: "ghijklmno", C: hexRange, Err: ErrDisallowedChars},
|
||||||
}
|
}
|
||||||
|
|
||||||
for n, tc := range testCases {
|
for n, tc := range testCases {
|
||||||
@@ -30,3 +31,30 @@ func TestChars(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExceptChars(t *testing.T) {
|
||||||
|
type TestCase struct {
|
||||||
|
Input string
|
||||||
|
C string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
hexRange := "0123456789abcdef"
|
||||||
|
|
||||||
|
testCases := []TestCase{
|
||||||
|
{Input: "abcd1234", C: hexRange, Err: ErrDisallowedChars},
|
||||||
|
{Input: "abcd 1234", C: hexRange, Err: ErrDisallowedChars},
|
||||||
|
{Input: "ghijklmno", C: hexRange},
|
||||||
|
}
|
||||||
|
|
||||||
|
for n, tc := range testCases {
|
||||||
|
t.Logf("(%d) Testing %q against %q", n, tc.Input, tc.C)
|
||||||
|
|
||||||
|
f := ExceptChars(tc.C)
|
||||||
|
err := f(tc.Input)
|
||||||
|
|
||||||
|
if !errors.Is(err, tc.Err) {
|
||||||
|
t.Errorf("Expected error %v, got %v", tc.Err, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user