Merge pull request #547 from atomicleads/master

Added boolean type support for “eq” validator
pull/564/head
Dean Karn 5 years ago committed by GitHub
commit 1d93fb999e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      baked_in.go
  2. 10
      util.go
  3. 19
      validator_test.go

@ -1106,6 +1106,11 @@ func isEq(fl FieldLevel) bool {
p := asFloat(param) p := asFloat(param)
return field.Float() == p return field.Float() == p
case reflect.Bool:
p := asBool(param)
return field.Bool() == p
} }
panic(fmt.Sprintf("Bad field type %T", field.Interface())) panic(fmt.Sprintf("Bad field type %T", field.Interface()))

@ -249,6 +249,16 @@ func asFloat(param string) float64 {
return i return i
} }
// asBool returns the parameter as a bool
// or panics if it can't convert
func asBool(param string) bool {
i, err := strconv.ParseBool(param)
panicIf(err)
return i
}
func panicIf(err error) { func panicIf(err error) {
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())

@ -7194,6 +7194,25 @@ func TestRequired(t *testing.T) {
AssertError(t, err.(ValidationErrors), "Test.Value", "Test.Value", "Value", "Value", "required") AssertError(t, err.(ValidationErrors), "Test.Value", "Test.Value", "Value", "Value", "required")
} }
func TestBoolEqual(t *testing.T) {
validate := New()
type Test struct {
Value bool `validate:"eq=true"`
}
var test Test
err := validate.Struct(test)
NotEqual(t, err, nil)
AssertError(t, err.(ValidationErrors), "Test.Value", "Test.Value", "Value", "Value", "eq")
test.Value = true
err = validate.Struct(test)
Equal(t, err, nil)
}
func TestTranslations(t *testing.T) { func TestTranslations(t *testing.T) {
en := en.New() en := en.New()
uni := ut.New(en, en, fr.New()) uni := ut.New(en, en, fr.New())

Loading…
Cancel
Save