From 0669d169a7d620c2865f850a39a069559694df38 Mon Sep 17 00:00:00 2001 From: aryehlev Date: Wed, 14 Sep 2022 18:56:19 +0300 Subject: [PATCH] add domain validation, allows most domains. --- baked_in.go | 6 ++++++ regexes.go | 2 ++ 2 files changed, 8 insertions(+) diff --git a/baked_in.go b/baked_in.go index f2f0939..7610567 100644 --- a/baked_in.go +++ b/baked_in.go @@ -122,6 +122,7 @@ var ( "email": isEmail, "url": isURL, "uri": isURI, + "domain": isDomain, "urn_rfc2141": isUrnRFC2141, // RFC 2141 "file": isFile, "base64": isBase64, @@ -1370,6 +1371,11 @@ func isURL(fl FieldLevel) bool { panic(fmt.Sprintf("Bad field type %T", field.Interface())) } +// isDomain is the validation function for validating if the current field's value is a valid domain. +func isDomain(fl FieldLevel) bool { + return domainRegex.MatchString(fl.Field().String()) +} + // isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. func isUrnRFC2141(fl FieldLevel) bool { field := fl.Field() diff --git a/regexes.go b/regexes.go index 9c1c634..ba2fdbf 100644 --- a/regexes.go +++ b/regexes.go @@ -64,6 +64,7 @@ const ( bicRegexString = `^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$` semverRegexString = `^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$` // numbered capture groups https://semver.org/ dnsRegexStringRFC1035Label = "^[a-z]([-a-z0-9]*[a-z0-9]){0,62}$" + domainRegexString = `^[a-z0-9-\.]{0,61}\.[a-z]{2,}$` ) var ( @@ -128,4 +129,5 @@ var ( bicRegex = regexp.MustCompile(bicRegexString) semverRegex = regexp.MustCompile(semverRegexString) dnsRegexRFC1035Label = regexp.MustCompile(dnsRegexStringRFC1035Label) + domainRegex = regexp.MustCompile(domainRegexString) )