diff --git a/opts/opts.go b/opts/opts.go index 4f5897c796..b2f21db30b 100644 --- a/opts/opts.go +++ b/opts/opts.go @@ -136,3 +136,16 @@ func ValidateIp4Address(val string) (string, error) { } return "", fmt.Errorf("%s is not an ip4 address", val) } + +func ValidateDomain(val string) (string, error) { + alpha := regexp.MustCompile(`[a-zA-Z]`) + if alpha.FindString(val) == "" { + return "", fmt.Errorf("%s is not a valid domain", val) + } + re := regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`) + var ns = re.FindSubmatch([]byte(val)) + if len(ns) > 0 { + return string(ns[1]), nil + } + return "", fmt.Errorf("%s is not a valid domain", val) +} diff --git a/opts/opts_test.go b/opts/opts_test.go index a5c1fac9ca..299cbfe503 100644 --- a/opts/opts_test.go +++ b/opts/opts_test.go @@ -22,3 +22,57 @@ func TestValidateIP4(t *testing.T) { } } + +func TestValidateDomain(t *testing.T) { + valid := []string{ + `a`, + `a.`, + `1.foo`, + `17.foo`, + `foo.bar`, + `foo.bar.baz`, + `foo.bar.`, + `foo.bar.baz`, + `foo1.bar2`, + `foo1.bar2.baz`, + `1foo.2bar.`, + `1foo.2bar.baz`, + `foo-1.bar-2`, + `foo-1.bar-2.baz`, + `foo-1.bar-2.`, + `foo-1.bar-2.baz`, + `1-foo.2-bar`, + `1-foo.2-bar.baz`, + `1-foo.2-bar.`, + `1-foo.2-bar.baz`, + } + + invalid := []string{ + ``, + `.`, + `17`, + `17.`, + `.17`, + `17-.`, + `17-.foo`, + `.foo`, + `foo-.bar`, + `-foo.bar`, + `foo.bar-`, + `foo.bar-.baz`, + `foo.-bar`, + `foo.-bar.baz`, + } + + for _, domain := range valid { + if ret, err := ValidateDomain(domain); err != nil || ret == "" { + t.Fatalf("ValidateDomain(`"+domain+"`) got %s %s", ret, err) + } + } + + for _, domain := range invalid { + if ret, err := ValidateDomain(domain); err == nil || ret != "" { + t.Fatalf("ValidateDomain(`"+domain+"`) got %s %s", ret, err) + } + } +}