Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added: len slice rule #12

Merged
merged 1 commit into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions len.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,10 @@ func (v *Validator) LenInt(i, size int, field, msg string) *Validator {

return v
}

// LenSlice checks if length of slice equal to size or not
func (v *Validator) LenSlice(s []any, size int, field, msg string) *Validator {
v.Check(len(s) == size, field, v.msg(Len, msg, field, size))

return v
}
47 changes: 47 additions & 0 deletions len_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,50 @@ func TestValidator_LenInt(t *testing.T) {
}
}
}

func TestValidator_LenSlice(t *testing.T) {
tests := []struct {
field string
value []any
len int
message string
isPassed bool
expectedMsg string
}{
{
field: "t0",
value: []any{1, 2, 3},
len: 3,
message: "",
isPassed: true,
expectedMsg: "",
},
{
field: "t1",
value: []any{1.1, 2.2, 7.9},
len: 5,
message: "",
isPassed: false,
expectedMsg: fmt.Sprintf(LenMsg, "t1", 5),
},
{
field: "t1",
value: []any{"a", "b", "c"},
len: 9,
message: "t2 must have len of 9",
isPassed: false,
expectedMsg: "t2 must have len of 9",
},
}

v := New()

for _, test := range tests {
v.LenSlice(test.value, test.len, test.field, test.message)

assert.Equal(t, test.isPassed, v.IsPassed())
if v.IsFailed() {
assert.Equal(t, test.expectedMsg, v.Errors()[test.field])
}
}
}
Loading