Fixed boolean validation to handle bool kind (#988)

pull/987/merge
Vaibhav Dighe 2 years ago committed by GitHub
parent 9e2ea40380
commit 1e8c614c2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 7
      baked_in.go
  2. 37
      validator_test.go

@ -1484,11 +1484,16 @@ func isAlphaUnicode(fl FieldLevel) bool {
return alphaUnicodeRegex.MatchString(fl.Field().String()) return alphaUnicodeRegex.MatchString(fl.Field().String())
} }
// isBoolean is the validation function for validating if the current field's value can be safely converted to a boolean. // isBoolean is the validation function for validating if the current field's value is a valid boolean value or can be safely converted to a boolean value.
func isBoolean(fl FieldLevel) bool { func isBoolean(fl FieldLevel) bool {
switch fl.Field().Kind() {
case reflect.Bool:
return true
default:
_, err := strconv.ParseBool(fl.Field().String()) _, err := strconv.ParseBool(fl.Field().String())
return err == nil return err == nil
} }
}
// isDefault is the opposite of required aka hasValue // isDefault is the opposite of required aka hasValue
func isDefault(fl FieldLevel) bool { func isDefault(fl FieldLevel) bool {

@ -8302,6 +8302,43 @@ func TestNumeric(t *testing.T) {
errs = validate.Var(i, "numeric") errs = validate.Var(i, "numeric")
Equal(t, errs, nil) Equal(t, errs, nil)
} }
func TestBoolean(t *testing.T) {
validate := New()
b := true
errs := validate.Var(b, "boolean")
Equal(t, errs, nil)
b = false
errs = validate.Var(b, "boolean")
Equal(t, errs, nil)
s := "true"
errs = validate.Var(s, "boolean")
Equal(t, errs, nil)
s = "false"
errs = validate.Var(s, "boolean")
Equal(t, errs, nil)
s = "0"
errs = validate.Var(s, "boolean")
Equal(t, errs, nil)
s = "1"
errs = validate.Var(s, "boolean")
Equal(t, errs, nil)
s = "xyz"
errs = validate.Var(s, "boolean")
NotEqual(t, errs, nil)
AssertError(t, errs, "", "", "", "", "boolean")
s = "1."
errs = validate.Var(s, "boolean")
NotEqual(t, errs, nil)
AssertError(t, errs, "", "", "", "", "boolean")
}
func TestAlphaNumeric(t *testing.T) { func TestAlphaNumeric(t *testing.T) {
validate := New() validate := New()

Loading…
Cancel
Save