Browse Source

add chars validation

Aneurin Barker Snook 1 year ago
parent
commit
b4b5b8b752
2 changed files with 54 additions and 0 deletions
  1. 19 0
      chars.go
  2. 35 0
      chars_test.go

+ 19 - 0
chars.go

@@ -0,0 +1,19 @@
+package validate
+
+import (
+	"fmt"
+	"strings"
+)
+
+// Chars validates whether a string contains only allowed characters.
+func Chars(allow string) func(string) error {
+	return func(value string) error {
+		rs := []rune(value)
+		for _, r := range rs {
+			if !strings.ContainsRune(allow, r) {
+				return fmt.Errorf("Contains disallowed characters")
+			}
+		}
+		return nil
+	}
+}

+ 35 - 0
chars_test.go

@@ -0,0 +1,35 @@
+package validate
+
+import "testing"
+
+func TestChars(t *testing.T) {
+	type TestCase struct {
+		C     string
+		Input string
+		Err   bool
+	}
+
+	hexRange := "0123456789abcdef"
+
+	testCases := []TestCase{
+		{C: hexRange, Input: "abcd1234"},
+		{C: hexRange, Input: "abcd 1234", Err: true},
+	}
+
+	for _, tc := range testCases {
+		t.Logf("%q contains only allowed characters %q", tc.Input, tc.C)
+
+		f := Chars(tc.C)
+		err := f(tc.Input)
+
+		if tc.Err {
+			if err == nil {
+				t.Error("Expected error; got nil")
+			}
+		} else {
+			if err != nil {
+				t.Errorf("Expected nil; got %s", err)
+			}
+		}
+	}
+}