From 70d0cd06f245743d69f699a8d35c777d79e67c86 Mon Sep 17 00:00:00 2001 From: nodivbyzero Date: Fri, 19 Jul 2024 17:21:55 -0700 Subject: [PATCH] feat: add validator for numeric ports --- baked_in.go | 8 ++++++++ validator_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/baked_in.go b/baked_in.go index b6fbaafa..a0b78a0c 100644 --- a/baked_in.go +++ b/baked_in.go @@ -213,6 +213,7 @@ var ( "json": isJSON, "jwt": isJWT, "hostname_port": isHostnamePort, + "port": isPort, "lowercase": isLowercase, "uppercase": isUppercase, "datetime": isDatetime, @@ -2704,6 +2705,13 @@ func isHostnamePort(fl FieldLevel) bool { return true } +// IsPort validates if the current field's value represents a valid port +func isPort(fl FieldLevel) bool { + val := fl.Field().Uint() + + return val >= 1 && val <= 65535 +} + // isLowercase is the validation function for validating if the current field's value is a lowercase string. func isLowercase(fl FieldLevel) bool { field := fl.Field() diff --git a/validator_test.go b/validator_test.go index 0f96b777..291d8e0a 100644 --- a/validator_test.go +++ b/validator_test.go @@ -12377,6 +12377,32 @@ func Test_hostnameport_validator(t *testing.T) { } } +func Test_port_validator(t *testing.T) { + type Host struct { + Port uint32 `validate:"port"` + } + + type testInput struct { + data uint32 + expected bool + } + testData := []testInput{ + {0, false}, + {1, true}, + {65535, true}, + {65536, false}, + {65538, false}, + } + for _, td := range testData { + h := Host{Port: td.data} + v := New() + err := v.Struct(h) + if td.expected != (err == nil) { + t.Fatalf("Test failed for data: %v Error: %v", td.data, err) + } + } +} + func TestLowercaseValidation(t *testing.T) { tests := []struct { param string