Validator: question: validate field if some other field == some value?

Created on 18 Jul 2019  路  4Comments  路  Source: go-playground/validator

Package version v9:

Question

type Config struct {
    EncryptionMode      string                  `yaml:"encryptionMode" validate="oneof=disabled legacyAES"`
    SecretKey           *config.SecretKeyConfig `yaml:"secretKey"`
}

I want to add validate tags to the SecretKey field, but i only want that to be validated if EncryptionMode == legacyAES, is that possible with the built in funcs? Or even i it possible to build a custom validator to do that generically? or does it have to be done as a struct level validator?

Thanks

enhancement

Most helpful comment

Thanks for the info @jdgordon @lbyte00
currently no there is no built-in functions to do this beyond StructLevel validation at this time.

I'm investigating options to support more expressive validations that have been being requested, without creating a customer syntax or query language, it is a breaking change though:

  • Merge field and struct validations into one to consolidate the interface and be able to perform custom validations on struct themselves, not just their fields.

The honest truth is I don't know when I'll be able to get to these changes as my plate is pretty full.

All 4 comments

You can define a custom struct validation function.
Example: https://github.com/go-playground/validator/blob/v9/_examples/struct-level/main.go#L37

@lbyte00 thanks, we were hoping to avoid doing that. Unlike the example we have dozens of small structs (nested) all over the code, and we are using a singlton validator object (created without visibility to every nested struct) and code standard is pushing us away from using init funcs to register them all.

Alternatively I was thinking about pushing a patch to attempt to cast each struct to a StructLevelValifator interface type to automatically call the validator func without needing registrations,. It sure how that would be received though.

@jdgordon yeah, I don't like this approach of defining custom struct validation functions too, and currently that's the only way that I found (had the same question as yours).

Thanks for the info @jdgordon @lbyte00
currently no there is no built-in functions to do this beyond StructLevel validation at this time.

I'm investigating options to support more expressive validations that have been being requested, without creating a customer syntax or query language, it is a breaking change though:

  • Merge field and struct validations into one to consolidate the interface and be able to perform custom validations on struct themselves, not just their fields.

The honest truth is I don't know when I'll be able to get to these changes as my plate is pretty full.

Was this page helpful?
0 / 5 - 0 ratings