validator icon indicating copy to clipboard operation
validator copied to clipboard

Validate struct bool field

Open mhclaudiu opened this issue 3 years ago • 4 comments

  • [x] I have looked at the documentation here first?
  • [x] I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

Hi, i searched but didn't found any docs related to this. How can we validate a bool field in struct?

Code sample, to showcase or reproduce:

type JsonStruct struct {
	Active bool   `validate:"required,bool"`
}
Undefined validation function 'bool' on field 'Active'

type JsonStruct struct {
	Active bool   `validate:"required,boolean"`
}
Undefined validation function 'boolean' on field 'Active'

type JsonStruct struct {
	Active bool   `validate:"required"`
}
If JsonStruct.Active is false, then i will get this:
    Key: 'JsonStruct.Active' Error:Field validation for 'Active' failed on the 'required' tag

mhclaudiu avatar Dec 13 '22 08:12 mhclaudiu

What is your expectation? How does the rest of the code look like? Can you Post a go playground link that demonstrates the issue?

hf-kklein avatar Dec 13 '22 16:12 hf-kklein

This problem is more significant and not only bool affected. You also can't use other basic types: int, float and string in their default value (https://github.com/go-playground/validator/blob/c7e0172e0fd176bdc521afb5186818a7db6b77ac/baked_in.go#L1504). Probably you can use the pointer to bool: type JsonStruct struct { Active *bool validate:"required" }

r2b89 avatar Dec 19 '22 20:12 r2b89

@hf-kklein are you kidding me? :) @r2b89 thank you, well this is weird.

mhclaudiu avatar Dec 20 '22 08:12 mhclaudiu

You're right. Sorry, didn't get the point during first read. The validator cannot distinguish between the field type default value False which is implicitly set if no value is provided in the JSON and the explicitly set value False. As r2b89 said, the solution is to make the field nullable. This avoids the ambiguity between default (now nil) and an explicitly set value. This problem is not specific to go or validator.

hf-kklein avatar Dec 20 '22 08:12 hf-kklein

Closing this as resolved

zemzale avatar Dec 27 '22 14:12 zemzale