go-playground / validator

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

[Q] required_if fieldname by JSON tag #1075

Closed mauserzjeh closed 1 year ago

mauserzjeh commented 1 year ago

Is it possible when using the required_if validator (or any other validator that will use another field as a parameter) to use the json tag value as a parameter instead of the field's name?

For example:

type MyStruct struct {
    AField string `json:"a_field"`
    BField string `json:"b_field" binding:"required_if=a_field foo"`
}

By default I can only use "required_if=AField foo" for the binding to make it work. Is it possible to somehow use the json tag value for a validator like this? So the binding would become "required_if=a_field foo"

I have already registered a TagNameFunc but I guess thats only works when returning error messages. Thanks in advance!

zemzale commented 1 year ago

Thanks for the question, but with default validators, it's not possible, but using a custom validation function you could do that if you really wish to. https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions