Skip to content

Commit 48992fa

Browse files
authored
feat: add validator for numeric ports (#1294)
## Fixes Or Enhances This PR adds a new validation for numeric ports. Connected to: #1216 ``` type Host struct { Port uint32 `validate:"port"` } ``` **Make sure that you've checked the boxes below before you submit PR:** - [x] Tests exist or have been written that cover this particular change. @go-playground/validator-maintainers
1 parent d7abf32 commit 48992fa

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

baked_in.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,7 @@ var (
214214
"json": isJSON,
215215
"jwt": isJWT,
216216
"hostname_port": isHostnamePort,
217+
"port": isPort,
217218
"lowercase": isLowercase,
218219
"uppercase": isUppercase,
219220
"datetime": isDatetime,
@@ -2729,6 +2730,13 @@ func isHostnamePort(fl FieldLevel) bool {
27292730
return true
27302731
}
27312732

2733+
// IsPort validates if the current field's value represents a valid port
2734+
func isPort(fl FieldLevel) bool {
2735+
val := fl.Field().Uint()
2736+
2737+
return val >= 1 && val <= 65535
2738+
}
2739+
27322740
// isLowercase is the validation function for validating if the current field's value is a lowercase string.
27332741
func isLowercase(fl FieldLevel) bool {
27342742
field := fl.Field()

validator_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12472,6 +12472,32 @@ func Test_hostnameport_validator(t *testing.T) {
1247212472
}
1247312473
}
1247412474

12475+
func Test_port_validator(t *testing.T) {
12476+
type Host struct {
12477+
Port uint32 `validate:"port"`
12478+
}
12479+
12480+
type testInput struct {
12481+
data uint32
12482+
expected bool
12483+
}
12484+
testData := []testInput{
12485+
{0, false},
12486+
{1, true},
12487+
{65535, true},
12488+
{65536, false},
12489+
{65538, false},
12490+
}
12491+
for _, td := range testData {
12492+
h := Host{Port: td.data}
12493+
v := New()
12494+
err := v.Struct(h)
12495+
if td.expected != (err == nil) {
12496+
t.Fatalf("Test failed for data: %v Error: %v", td.data, err)
12497+
}
12498+
}
12499+
}
12500+
1247512501
func TestLowercaseValidation(t *testing.T) {
1247612502
tests := []struct {
1247712503
param string

0 commit comments

Comments
 (0)