From f2ebb457570c4bb651b19388f84be1a7a3deb4d5 Mon Sep 17 00:00:00 2001 From: zengwh Date: Fri, 18 Sep 2020 17:29:03 +0800 Subject: [PATCH] fix url validation (#38) --- binding.go | 2 +- common_test.go | 4 ++++ validate_test.go | 20 ++++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/binding.go b/binding.go index ddba87f..172c9c4 100644 --- a/binding.go +++ b/binding.go @@ -301,7 +301,7 @@ var ( urlSubdomainRx = `((www\.)|([a-zA-Z0-9]([-\.][-\._a-zA-Z0-9]+)*))` urlPortRx = `(:(\d{1,5}))` urlPathRx = `((\/|\?|#)[^\s]*)` - URLPattern = regexp.MustCompile(`^` + urlSchemaRx + `?` + urlUsernameRx + `?` + `((` + urlIPRx + `|(\[` + ipRx + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + urlSubdomainRx + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + urlPortRx + `?` + urlPathRx + `?$`) + URLPattern = regexp.MustCompile(`^` + urlSchemaRx + urlUsernameRx + `?` + `((` + urlIPRx + `|(\[` + ipRx + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + urlSubdomainRx + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + urlPortRx + `?` + urlPathRx + `?$`) ) // IsURL check if the string is an URL. diff --git a/common_test.go b/common_test.go index 502ef9d..4e84f62 100755 --- a/common_test.go +++ b/common_test.go @@ -83,6 +83,10 @@ type ( People []Person `json:"people" binding:"MinSize(1)"` } + UrlForm struct { + Url string `form:"Url" binding:"Url"` + } + CustomErrorHandle struct { Rule `binding:"CustomRule"` } diff --git a/validate_test.go b/validate_test.go index 55e6a4d..b0da173 100755 --- a/validate_test.go +++ b/validate_test.go @@ -370,6 +370,26 @@ var validationTestCases = []validationTestCase{ }, }, }, + { + description: "invalid url Validation", + data: UrlForm{ + Url: "192.168.0.1", + }, + expectedErrors: Errors{ + Error{ + FieldNames: []string{"Url"}, + Classification: "Url", + Message: "Url", + }, + }, + }, + { + description: "valid url Validation", + data: UrlForm{ + Url: "https://192.168.0.1:8000", + }, + expectedErrors: Errors{}, + }, } func Test_Validation(t *testing.T) {