go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.83k stars 1.32k forks source link

Validate struct bool field #1040

Closed mhclaudiu closed 1 year ago

mhclaudiu commented 1 year ago

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
hf-kklein commented 1 year ago

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

r2b89 commented 1 year ago

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 *boolvalidate:"required" }

mhclaudiu commented 1 year ago

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

hf-kklein commented 1 year ago

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.

zemzale commented 1 year ago

Closing this as resolved