Skip to content

Commit

Permalink
Merge pull request #10 from amirmms/fix-max-messages
Browse files Browse the repository at this point in the history
fixed: max default messages
  • Loading branch information
rezakhademix authored Mar 4, 2024
2 parents f6d4cb6 + a853d7e commit f342c3e
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 5 deletions.
16 changes: 15 additions & 1 deletion max.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
package validator

const (
// Max represents the rule name which will be used to find the default error message.
Max = "max"
// MaxMsg is the default error message format for len rule.
MaxMsg = "%s should less than %v"
)

// MaxInt checks i to be less than max value
func (v *Validator) MaxInt(i, max int, field, msg string) *Validator {
v.Check(i <= max, field, msg)
v.Check(i <= max, field, v.msg(Max, msg, field, max))

return v
}

// MaxFloat64 checks i to be less than max value
func (v *Validator) MaxFloat64(i, max float64, field, msg string) *Validator {
v.Check(i <= max, field, v.msg(Max, msg, field, max))

return v
}
56 changes: 52 additions & 4 deletions max_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@ func TestValidator_MaxInt(t *testing.T) {
field: "t1",
value: 1,
max: 0,
message: "t1 must be less than 0",
message: "",
isPassed: false,
expectedMsg: "t1 must be less than 0",
expectedMsg: "t1 should less than 0",
},
{
field: "t2",
value: 122,
max: 20,
message: "t1 must be less than 20",
message: "t2 must be less than 20",
isPassed: false,
expectedMsg: "t1 must be less than 20",
expectedMsg: "t2 must be less than 20",
},
}

Expand All @@ -53,3 +53,51 @@ func TestValidator_MaxInt(t *testing.T) {
}
}
}

func TestValidator_MaxFloat64(t *testing.T) {
tests := []struct {
field string
value float64
max float64
message string
isPassed bool
expectedMsg string
}{
{
field: "t0",
value: 10.1,
max: 10.8,
message: "",
isPassed: true,
expectedMsg: "",
},
{
field: "t1",
value: 0.1,
max: 0.01,
message: "",
isPassed: false,
expectedMsg: "t1 should less than 0.01",
},
{
field: "t2",
value: 122,
max: 20,
message: "t2 must be less than 20",
isPassed: false,
expectedMsg: "t2 must be less than 20",
},
}

v := New()

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

assert.Equal(t, test.isPassed, v.IsPassed())

if !test.isPassed {
assert.Equal(t, test.expectedMsg, v.Errors()[test.field])
}
}
}
1 change: 1 addition & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ var (
methodToErrorMessage = map[string]string{
Required: RequiredMsg,
Len: LenMsg,
Max: MaxMsg,
Min: MinMsg,
Between: BetweenMsg,
}
Expand Down

0 comments on commit f342c3e

Please sign in to comment.