Skip to content

Commit

Permalink
feat: add validator for numeric ports (#1294)
Browse files Browse the repository at this point in the history
## 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
  • Loading branch information
nodivbyzero authored Nov 16, 2024
1 parent d7abf32 commit 48992fa
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ var (
"json": isJSON,
"jwt": isJWT,
"hostname_port": isHostnamePort,
"port": isPort,
"lowercase": isLowercase,
"uppercase": isUppercase,
"datetime": isDatetime,
Expand Down Expand Up @@ -2729,6 +2730,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()
Expand Down
26 changes: 26 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12472,6 +12472,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
Expand Down

0 comments on commit 48992fa

Please sign in to comment.