Skip to content

Commit 1d93fb9

Browse files
author
Dean Karn
authored
Merge pull request #547 from atomicleads/master
Added boolean type support for “eq” validator
2 parents 5356060 + d149847 commit 1d93fb9

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

baked_in.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,6 +1106,11 @@ func isEq(fl FieldLevel) bool {
11061106
p := asFloat(param)
11071107

11081108
return field.Float() == p
1109+
1110+
case reflect.Bool:
1111+
p := asBool(param)
1112+
1113+
return field.Bool() == p
11091114
}
11101115

11111116
panic(fmt.Sprintf("Bad field type %T", field.Interface()))

util.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,16 @@ func asFloat(param string) float64 {
249249
return i
250250
}
251251

252+
// asBool returns the parameter as a bool
253+
// or panics if it can't convert
254+
func asBool(param string) bool {
255+
256+
i, err := strconv.ParseBool(param)
257+
panicIf(err)
258+
259+
return i
260+
}
261+
252262
func panicIf(err error) {
253263
if err != nil {
254264
panic(err.Error())

validator_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7194,6 +7194,25 @@ func TestRequired(t *testing.T) {
71947194
AssertError(t, err.(ValidationErrors), "Test.Value", "Test.Value", "Value", "Value", "required")
71957195
}
71967196

7197+
func TestBoolEqual(t *testing.T) {
7198+
7199+
validate := New()
7200+
7201+
type Test struct {
7202+
Value bool `validate:"eq=true"`
7203+
}
7204+
7205+
var test Test
7206+
7207+
err := validate.Struct(test)
7208+
NotEqual(t, err, nil)
7209+
AssertError(t, err.(ValidationErrors), "Test.Value", "Test.Value", "Value", "Value", "eq")
7210+
7211+
test.Value = true
7212+
err = validate.Struct(test)
7213+
Equal(t, err, nil)
7214+
}
7215+
71977216
func TestTranslations(t *testing.T) {
71987217
en := en.New()
71997218
uni := ut.New(en, en, fr.New())

0 commit comments

Comments
 (0)